Testing Django Wizard Views - django

I'm writing tests for my wizard using this excellent example from PyDoc.net.
One of the methods in my TestCase is not returning the correct step in the wizard:
class WizardTests(TestCase):
wizard_step_data = (
{
'step2-address': '123 Anywhere Ln.'
'wizard_wizard-current_step': 'step2'
},
)
def test_form_post_success(self):
response = self.client.post('/wizard/new/step2', self.wizard_step_data[0])
wizard = response.context['wizard']
self.assertEqual(response.status_code, 200)
self.assertEqual(wizard['steps'].current, 'step2')
When I run this, I get back:
Traceback (most recent call last):
File "/var/www/app/wizard/tests.py", line 71, in test_form_post_success
self.assertEqual(wizard['steps'].current, 'step2')
AssertionError: 'step1' != 'step2'
I am using a NamedUrlSessionWizardView, which is why my URL on the self.client.post is /wizard/new/step2, as opposed to just /wizard/ like the example above. Otherwise, I receive 404's, or 301's for /wizard/new.
Do you have any ideas about what could be causing this?

Related

Error while accessing Google Contacts Groups by API

I want get list of all groups in my contacts. I use that code:
import gdata.gauth
import gdata.contacts.client
token = gdata.gauth.OAuth2Token(client_id = "***.apps.googleusercontent.com",
client_secret = "***",
scope = "https://www.google.com/m8/feeds/",
user_agent = "GC")
gd_client = gdata.contacts.client.ContactsClient(source = 'GCv0.1')
gd_client = token.authorize(gd_client)
gd_client.GetGroups()
But got error:
Traceback (most recent call last):
File "F:/Yandex/Sites/GoogleContacts/cli_contacts.py", line 27, in <module>
gd_client.GetGroups()
File "C:\Users\Ishayahu\27Gdata\lib\site-packages\gdata\contacts\client.py", line 218, in get_groups
return self.get_feed(uri, desired_class=desired_class, auth_token=auth_token, **kwargs)
File "C:\Users\Ishayahu\27Gdata\lib\site-packages\gdata\client.py", line 640, in get_feed
**kwargs)
File "C:\Users\Ishayahu\27Gdata\lib\site-packages\gdata\client.py", line 319, in request
RequestError)
gdata.client.RequestError: Server responded with: 400,
enter code here
I have no idea what a reason and I can't find any clue how to solve it.
UPD: It looks like I should somehow put acess_token or refresh_token into OAuth2Token, but I can't understand how
so it send headers
{'GData-Version': '3', 'Authorization': 'Bearer None', 'User-Agent': 'gdata-py/2.0.17'}
UPD2: by the way, if I test in in OAuth2Playground, it shows me a page with request access to my contacts. That script doesn't ask for it. Maybe that's the problem? How can I change it? I thought, it connect with url_redirect, but I can't uderstand, how to use it
UPD3: I was right: if I add access_token, which I get manualy from Playground, all works. But how should I get it in script?!

Encountering remote error using grpc with protobuf2.6 in python

I am using grpc with protobuf 2.6.1 in python 2.7, and when I run my client side code, I have the following errors:
Traceback (most recent call last):
File "debate_client.py", line 31, in <module>
run_client()
File "debate_client.py", line 17, in run_client
reply = stub.Answer(debate_pb2.AnswerRequest(question=question, timeout=timeout), 30)
File "/Users/elaine/Desktop/gitHub/grpc/python2.7_virtual_environment/lib/python2.7/site-packages/grpc/framework/crust/implementations.py", line 73, in __call__
protocol_options, metadata, request)
File "/Users/elaine/Desktop/gitHub/grpc/python2.7_virtual_environment/lib/python2.7/site-packages/grpc/framework/crust/_calls.py", line 109, in blocking_unary_unary
return next(rendezvous)
File "/Users/elaine/Desktop/gitHub/grpc/python2.7_virtual_environment/lib/python2.7/site-packages/grpc/framework/crust/_control.py", line 412, in next
raise self._termination.abortion_error
grpc.framework.interfaces.face.face.RemoteError: RemoteError(code=StatusCode.UNKNOWN, details="")
Here is my client side code:
from grpc.beta import implementations
import debate_pb2
import sys
def run_client():
params = sys.argv
print params
how = params[1]
question = params[2]
channel = implementations.insecure_channel('localhost', 29999)
stub = debate_pb2.beta_create_Candidate_stub(channel)
if how.lower() == "answer":
timeout = int(params[3])
reply = stub.Answer(debate_pb2.AnswerRequest(question=question, timeout=timeout), 30)
elif how.lower() == "elaborate":
blah = params[3:len(sys.argv)]
for i in range(0, len(blah)):
blah[i] = int(blah[i])
reply = stub.Elaborate(debate_pb2.ElaborateRequest(topic=question, blah_run=blah), 30)
if reply is None:
print "No comment"
else:
print reply.answer
if __name__ == "__main__":
run_client()
And here is my server side code:
import debate_pb2
import consultation_pb2
import re
import random
from grpc.beta import implementations
class Debate(debate_pb2.BetaCandidateServicer):
def Answer(self, request, context=None):
#Answer implementation
def Elaborate(self, request, context=None):
#Elaborate implementation
def run_server():
server = debate_pb2.beta_create_Candidate_server(Debate())
server.add_insecure_port('localhost:29999')
server.start()
if __name__ == "__main__":
run_server()
Any idea where the remote error comes from? Thank you so much!
Hello Elaine and thank you for trying out gRPC Python.
Nothing leaps out at me as an obvious smoking gun, but a couple of things I see are:
gRPC Python isn't known to work with protobuf 2.6.1. Have you tried working with the very latest protobuf release (3.0.0a3 at this time)?
context isn't an optional keyword parameter in servicer methods; it's a required, positional parameter. Does dropping =None from your servicer method implementations effect any change?
The same happened to me just now, and I figured out why.
Make sure the messages in your proto definition and the message in your implementations match the format.
For example, my Response message had a message= param in my python server, but not in my proto definition.
I think your function implementations should be outside class Debate or might be your functions are not correctly implemented to give the desired result.
I faced a similar error because my functions were inside the class but moving it outside the class fixed it.

Getting Attachments From Outlook 2010 With Python

I have the following script, which is trying to get attachments from Outlook.
outlook = win32com.client.Dispatch("Outlook.Application")
inbox = outlook.GetDefaultFolder(0)
messages = inbox.Items
message = messages.GetLast() #open last message
attachments = message.Attachments #assign attachments to attachment variable
attachment = attachments.Item(1)
attachment.SaveASFile(os.path.join('c:', 'temp'))
When I run it however I am getting the following:
Traceback (most recent call last):
File "C:/Users/e003048/QA/trunk/automation/selenium/src/global_functions/util_get_email_attachments.py", line 11, in <module>
inbox = outlook.GetDefaultFolder(0)
File "C:\Python27\Lib\site-packages\win32com\client\dynamic.py", line 522, in __getattr__
raise AttributeError("%s.%s" % (self._username_, attr))
AttributeError: Outlook.Application.GetDefaultFolder
I am unsure where I would put the username to get this to work.
I tried the suggestion in the answer below and am getting the following error:
Traceback (most recent call last):
File "C:/Users/e003048/QA/trunk/automation/selenium/src/global_functions/util_get_email_attachments.py", line 10, in <module>
inbox = mapi.GetDefaultFolder(0)
File "<COMObject <unknown>>", line 2, in GetDefaultFolder
pywintypes.com_error: (-2147024809, 'The parameter is incorrect.', None, None)
I wanted to include my completed working code in-case anyone else will find it useful:
def get_email_attachments(self):
outlook = win32com.client.Dispatch("Outlook.Application").GetNameSpace('MAPI')
# change the Folders parameter to the directory you are having the attachment go to
inbox = outlook.GetDefaultFolder(6).Folders('ForAttachments')
messages = inbox.Items
message = messages.GetLast() # opens the last message
attachments = message.Attachments
attachment = attachments.Item(1)
attachment.SaveAsFile('C:\\temp\\' + attachment.FileName)
The GetDefaultFolder is not defined on the application object (see application docs), it is defined on the NameSpace object which you get via
mapi = outlook.GetNameSpace("MAPI")
Then
inbox = mapi.GetDefaultFolder(0)
I think you can also use
mapi = outlook.Session
instead of GetNameSpace.

How to assert in django that F is only one time in ABCDEF

how do i assert that F appears only once in ABCDEF?
I used assertEqual but django states that:
Traceback (most recent call last):
File "/Users/jorrit/virtualenvs/voetbabbel/voetbabbel/apps/mass_mailer/tests.py", line 61, in test_create_mailing_list
self.assertContains(p.user.email,"#", 1, status_code=200)
File "/Library/Python/2.7/site-packages/django/test/testcases.py", line 419, in assertContains
self.assertEqual(response.status_code, status_code,
AttributeError: 'unicode' object has no attribute 'status_code'
and my code in the test:
self.assertContains(p.user.email,"#", 1)
assertContains is not for test random strings. It's for testing the response from view -- specifically that the response contains a certain bit of text. If you're not using a TestClient and testing against the response from one of your views, you can't use it.
Check out assertEqual. This is how the Django testing docs test for this sort of thing. Using assertEqual in this way will give you a little more feedback that assertTrue on failure.
self.assertEqual(p.user.email.count('#'), 1)
As Chris says, this isn't what assertContains is for. You can use one of the standard assertions:
self.assertTrue(p.user.email.count('#') == 1)

Unit testing in Web2py

I'm following the instructions from this post but cannot get my methods recognized globally.
The error message:
ERROR: test_suggest_performer (__builtin__.TestSearch)
----------------------------------------------------------------------
Traceback (most recent call last):
File "applications/myapp/tests/test_search.py", line 24, in test_suggest_performer
suggs = suggest_flavors("straw")
NameError: global name 'suggest_flavors' is not defined
My test file:
import unittest
from gluon.globals import Request
db = test_db
execfile("applications/myapp/controllers/search.py", globals())
class TestSearch(unittest.TestCase):
def setUp(self):
request = Request()
def test_suggest_flavors(self):
suggs = suggest_flavors("straw")
self.assertEqual(len(suggs), 1)
self.assertEqual(suggs[0][1], 'Strawberry')
My controller:
def suggest_flavors(term):
return []
Has anyone successfully completed unit testing like this in web2py?
Please see: http://web2py.com/AlterEgo/default/show/260
Note that in your example the function 'suggest_flavors' should be defined at 'applications/myapp/controllers/search.py'.
I don't have any experience with web2py, but used other frameworks a lot. And looking at your code I'm confused a bit. Is there an objective reason why execfile should be used? Isn't it better to use regular import statement. So instead of execfile you may write:
from applications.myapp.controllers.search import suggest_flavors
It's more clear code for pythoners.
Note, that you should place __init__.py in each directory along the path in this case, so that dirs will form package/module hierarchy.