How to pass list for testing in python? - python-2.7

I have created two dictionary in python
self.post_data={
'name' : 'Org 1',
'url' : 'http://www.org1.com',
'summary' : 'This is an example org1'
}
second
self.post_data1={
'name' : 'Org 2',
'url' : 'http://www.org2.com',
'summary' : 'This is an example org2'
}
Now my test_post_list function is
def test_post_list(self):
self.create_session()
self.assertEqual(Org.objects.count(), 0)
self.assertHttpCreated(self.api_client.post('/members/api/v1/org/', format='json', data=[{self.post_data},{self.post_data1}]))
self.assertEqual(Org.objects.count(), 1)
if I pass data like this to test case, it raises an error
>ERROR: test_post_list (members.tests.test_org_resource.OrgTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Users\Sanky\amber\members\tests\test_org_resource.py", line 51, in te
st_post_list
self.assertHttpCreated(self.api_client.post('/members/api/v1/org/', format='json', data={self.post_data,self.post_data1}))
TypeError: unhashable type: 'dict'`
How I will be able to pass list as data to test function.

Do something like this
data=[self.post_data,self.post_data1]
instead of this --
data=[{self.post_data},{self.post_data1}]
i.e no need to include dictionary inside {}

Related

Testing Django Wizard Views

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?

python sqlite3 .executemany() with named placeholders?

This works:
ss = 'insert into images (file_path) values(?);'
dddd = (('dd1',), ('dd2',))
conn.executemany(ss, dddd)
However this does not:
s = 'insert into images (file_path) values (:v)'
ddddd = ({':v': 'dd11'}, {':v': 'dd22'})
conn.executemany(s, ddddd)
Traceback (most recent call last):
File "/Users/Wes/.virtualenvs/ppyy/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 3035, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-31-a999de59f73b>", line 1, in <module>
conn.executemany(s, ddddd)
ProgrammingError: You did not supply a value for binding 1.
I am wondering if it is possible to use named parameters with executemany and, if so, how.
The documentation at section 11.13.3 talks generally about parameters but doesn't discuss the two styles of parameters that are described for other flavors of .executexxx().
I have checked out Python sqlite3 execute with both named and qmark parameters which does not pertain to executemany.
The source shows that execute() simply constructs a one-element list and calls executemany(), so the problem is not with executemany() itself; the same call fails with execute():
>>> conn.execute('SELECT :v', {':v': 42})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
sqlite3.ProgrammingError: You did not supply a value for binding 1.
As shown in the Python documentation, named parameters do not include the colon:
# And this is the named style:
cur.execute("select * from people where name_last=:who and age=:age", {"who": who, "age": age})
So you have to use ddddd = ({'v': 'dd11'}, {'v': 'dd22'}).
The : isn't part of the parameter name.
>>> s = 'insert into images (file_path) values (:v)'
>>> ddddd = ({'v': 'dd11'}, {'v': 'dd22'})
>>> conn.executemany(s, ddddd)
<sqlite3.Cursor object at 0x0000000002C0E500>
>>> conn.execute('select * from images').fetchall()
[(u'dd11',), (u'dd22',)]

Having difficult time parsing this string with regex?

text="""[{"token":"03AJzQf7P5tfAY0T8yGDlF_aoPkLgz9-F7aiXzvViQqaaRmcJeFuIq96vmLoPXVK1GW-Fs8xp6OmJWvFvyNa3ayMpvaLkb6R sVkjjWBjqVIW4ziWeHk--Vrd8zVaA-Pt8VxMdoDBYxjRRrCNdeQN-Fk_-Wywb5XceJGdPJbMDZ-BoOB8l3Gq4bFwJTVu56zLT-4fbAsLWqRI7TjEswJ_y2-6NlEOyTTxFblzlZLYFh7urRx2Wra_gdP0-uUxoZydZBzbiPetcYmGo9b1B69-Pmb7akK7aqLUN03mvC3t1bn4u0ZvJGWjBmqhv81QoP3J1u-_Xh p34_dhspsjDpgfxYcHTI3e3yAir_QQ","timestamp":"2017-10-11T23:40:13.436Z"},{"token":"03AJzQf7Mmj_KZVl39Ob1_YnvsJuj4vFS o8ZWXNUJjSEjZqNyH8puB035sZYbQdPLVdOoX8ljyGeDYvxk6Kkf3Sc16EAS0bg0cXUAXzs6LAr3jDZmtW38TjWN5qbykIN_-s0-YpX6F0XJ4Hw3GDl vVkxmAk1btZewbeUp1nwMeM9BGJxkJZ5_2LRCGTERPGICKU4P897_FYcduADw5j1wEd9Yp7TdczRkgkY3qpsNcxlrF_rXv7DAvUxkg2_fussc3RkRgq ZueTMPkDN7B5BYiTBqVeXJ48Lvm6-1R86HgyrcDAPaZ1xMY0JxzMSvU26rChpomXFLERLfxijDNrixfGeh8hSCa0dX1HiLac8yOERKRcbBk1kXLOK8" ,"timestamp":"2017-10-11T23:40:29.916Z"}]"""
I would like to parse out this string, and put it into a list. I only want the token value to be store in the list.
My current code (not working):
token = re.search('(?<="token":").*?"', text)
print(token.group(0))
print(token.group(1))
the output:
03AJzQf7P5tfAY0T8yGDlF_aoPkLgz9-F7aiXzvViQqaaRmcJeFuIq96vmLoPXVK1GW-Fs8xp6OmJWvFvyNa3ayMpvaLkb6RsVkjjWBjqVIW4ziWeHk--Vrd8zVaA-Pt8VxMdoDBYxjRRrCNdeQN-Fk_-Wywb5XceJGdPJbMDZ-BoOB8l3Gq4bFwJTVu56zLT-4fbAsLWqRI7TjEswJ_y2-6NlEOyTTxFblzlZLYFh7urRx2Wra_gdP0-uUxoZydZBzbiPetcYmGo9b1B69-Pmb7akK7aqLUN03mvC3t1bn4u0ZvJGWjBmqhv81QoP3J1u-_Xhp34_dhspsjDpgfxYcHTI3e3yAir_QQ"
Error for token.group(1):
Traceback (most recent call last):
File "main.py", line 45, in <module>
print(token.group(1))
IndexError: no such groupuUxoZydZBzbiPetcYmGo9b1B69-Pmb7akK7aqLUN03mvC3t1bn4u0ZvJGWjBmqhv81QoP3J1u-_Xhp34_dhspsjDpgfxYcHTI3e3yAir_QQ"
Your text is a json string. You can use json.loads to convert from json string to a list of dict.
import json
text="""[{"token":"03AJzQf7P5tfAY0T8yGDlF_aoPkLgz9-F7aiXzvViQqaaRmcJeFuIq96vmLoPXVK1GW-Fs8xp6OmJWvFvyNa3ayMpvaLkb6R sVkjjWBjqVIW4ziWeHk--Vrd8zVaA-Pt8VxMdoDBYxjRRrCNdeQN-Fk_-Wywb5XceJGdPJbMDZ-BoOB8l3Gq4bFwJTVu56zLT-4fbAsLWqRI7TjEswJ_y2-6NlEOyTTxFblzlZLYFh7urRx2Wra_gdP0-uUxoZydZBzbiPetcYmGo9b1B69-Pmb7akK7aqLUN03mvC3t1bn4u0ZvJGWjBmqhv81QoP3J1u-_Xh p34_dhspsjDpgfxYcHTI3e3yAir_QQ","timestamp":"2017-10-11T23:40:13.436Z"},{"token":"03AJzQf7Mmj_KZVl39Ob1_YnvsJuj4vFS o8ZWXNUJjSEjZqNyH8puB035sZYbQdPLVdOoX8ljyGeDYvxk6Kkf3Sc16EAS0bg0cXUAXzs6LAr3jDZmtW38TjWN5qbykIN_-s0-YpX6F0XJ4Hw3GDl vVkxmAk1btZewbeUp1nwMeM9BGJxkJZ5_2LRCGTERPGICKU4P897_FYcduADw5j1wEd9Yp7TdczRkgkY3qpsNcxlrF_rXv7DAvUxkg2_fussc3RkRgq ZueTMPkDN7B5BYiTBqVeXJ48Lvm6-1R86HgyrcDAPaZ1xMY0JxzMSvU26rChpomXFLERLfxijDNrixfGeh8hSCa0dX1HiLac8yOERKRcbBk1kXLOK8" ,"timestamp":"2017-10-11T23:40:29.916Z"}]"""
mylist = json.loads(text)
token = ' '.join(mylist[0]['token'].split()).split()

My first unit test, what am I doing wrong?

This is my first time trying to write a test and I'm guessing I made some obvious screw up with writing the test itself.
Here is my test:
from django.test import TestCase
from accounts.forms import UserReview
class MyTests(TestCase):
def test_forms(self):
form_data = {'headline': 'test', 'body_text': 'description of item Im selling', 'author: ben'}
form = SellForm(data=form_data)
self.assertEqual(form.is_valid(), True)
I am getting the following error:
ImportError: Failed to import test module: accounts.tests
Traceback (most recent call last):
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/loader.py", line 254, in _find_tests
module = self._get_module_from_name(name)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/loader.py", line 232, in _get_module_from_name
__import__(name)
File "/Users/benjamino/Desktop/myproject/myproject/accounts/tests.py", line 8
form_data = {'headline': 'test', 'body_text': 'description of item Im selling', 'author: ben'}
^
SyntaxError: invalid syntax
----------------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (errors=1)
Destroying test database for alias 'default'...
Why is accounts.tests failing to import? The code above is located in my accounts/tests.py.
The exception is clear on where the error is :
File "/Users/benjamino/Desktop/myproject/myproject/accounts/tests.py", line 8
form_data = {'headline': 'test', 'body_text': 'description of item Im selling', 'author: ben'}
^
SyntaxError: invalid syntax
Take a better look at the form_data: {'headline': 'test', 'body_text': 'description of item Im selling', 'author: ben'} (you have included a string instead of a name: value pair in your dict)
This is a simple syntax error, as the message tells you. Your quoting is wrong in the last element of your dict: 'author: ben' should be 'author': 'ben'
It's clear from the exception itself that the error is in your syntax. The form data format should be {name : value} but in your case it's {'string : value'} and if that doesn't solved your problem,maybe this could help you
Link

Why does a failing test with mox fail other tests as well?

My issue is quite simple: I'm having a bunch of unit tests using pymox. When I add a new test that fails, most of the time a whole lot of others fail as well. How can I prevent that from happening?
For example, I have a simple script for which I have two unit tests:
def test_main_returnsUnknown_ifCalculator_returnsMinus1(self):
m=mox.Mox()
m.StubOutWithMock(check_es_insert,"getArgs")
check_es_insert.getArgs(\
'Nagios plugin for checking the total number of documents stored in Elasticsearch')\
.AndReturn({ 'critical' : 7, 'warning' : 5, 'address' : 'myhost:1234', 'file' : '/tmp/bla'})
################
#some other mocking here, not relevant, I think
################
m.ReplayAll()
#now let's test
check_es_docs.main()
#verify and cleanup
m.UnsetStubs()
m.VerifyAll()
m.ResetAll()
def test_main_doesWhatPrintAndExitSays_inNormalConditions(self):
m=mox.Mox()
m.StubOutWithMock(check_es_insert,"getArgs")
check_es_insert.getArgs(\
'Nagios plugin for checking the total number of documents stored in Elasticsearch')\
.AndReturn({ 'critical' : 7, 'warning' : 5, 'address' : 'myhost:1234', 'file' : '/tmp/bla'})
################
#some other mocking here, not relevant, I think
################
m.ReplayAll()
#now let's test
check_es_docs.main()
#verify and clean up
m.UnsetStubs()
m.VerifyAll()
m.ResetAll()
Normally, both tests pass, but if I sneak in a typo on my second tests, I get this output when running the tests:
$ ./check_es_docs.test.py
FE
======================================================================
ERROR: test_main_returnsUnknown_ifCalculator_returnsMinus1 (__main__.Main)
If it can't get the current value from ES, print an error message and exit 3
----------------------------------------------------------------------
Traceback (most recent call last):
File "./check_es_docs.test.py", line 13, in test_main_returnsUnknown_ifCalculator_returnsMinus1
m.StubOutWithMock(check_es_insert,"getArgs")
File "/usr/local/lib/python2.7/dist-packages/mox-0.5.3-py2.7.egg/mox.py", line 312, in StubOutWithMock
raise TypeError('Cannot mock a MockAnything! Did you remember to '
TypeError: Cannot mock a MockAnything! Did you remember to call UnsetStubs in your previous test?
======================================================================
FAIL: test_main_doesWhatPrintAndExitSays_inNormalConditions (__main__.Main)
If getCurrent returns a positive value, main() should print the text and exit with the code Calculator.printandexit() says
----------------------------------------------------------------------
Traceback (most recent call last):
File "./check_es_docs.test.py", line 69, in test_main_doesWhatPrintAndExitSays_inNormalConditions
check_es_docs.main()
File "/home/radu/check_es_docs.py", line 25, in main
check_es_insert.printer("Total number of documents in Elasticsearch is %d | 'es_docs'=%d;%d;%d;;" % (result,result,cmdline['warning'],cmdline['critical']))
File "/usr/local/lib/python2.7/dist-packages/mox-0.5.3-py2.7.egg/mox.py", line 765, in __call__
return mock_method(*params, **named_params)
File "/usr/local/lib/python2.7/dist-packages/mox-0.5.3-py2.7.egg/mox.py", line 1002, in __call__
expected_method = self._VerifyMethodCall()
File "/usr/local/lib/python2.7/dist-packages/mox-0.5.3-py2.7.egg/mox.py", line 1060, in _VerifyMethodCall
raise UnexpectedMethodCallError(self, expected)
UnexpectedMethodCallError: Unexpected method call. unexpected:- expected:+
- printer.__call__("Total number of documents in Elasticsearch is 3 | 'es_docs'=3;5;7;;") -> None
? -
+ printer.__call__("Total nuber of documents in Elasticsearch is 3 | 'es_docs'=3;5;7;;") -> None
----------------------------------------------------------------------
Ran 2 tests in 0.002s
FAILED (failures=1, errors=1)
The first test should have passed with no error, since it wasn't changed a bit. check_es_insert.getArgs() shouldn't be a MockAnything instance, and I didn't forget to call UnsetStubs. I've searched quite a lot and I didn't find other people with the same problem. So I guess I'm missing something pretty obvious...
Additional info:
check_es_docs is the script I'm testing
check_es_insert is another script from which I'm importing a lot of stuff
I've tried putting UnsetStubs() after VerifyAll() with the same results
I've tried initializing the mox.Mox() object from the SetUp method, and also putting the cleanup stuff in TearDown, with the same results
I would recommend putting all of your tests into test classes that extend TestCase and then add in an UnsetStubs in the tearDown method:
from unittest import TestCase
import mox
class MyTestCasee(TestCase):
def __init__(self, testCaseName):
self.m = mox.Mox()
TestCase.__init__(self, testCaseName)
def tearDown(self):
self.m.UnsetStubs()
def test_main_returnsUnknown_ifCalculator_returnsMinus1(self):
self.m.StubOutWithMock(check_es_insert,"getArgs")
check_es_insert.getArgs(\
'Nagios plugin for checking the total number of documents stored in Elasticsearch')\
.AndReturn({ 'critical' : 7, 'warning' : 5, 'address' : 'myhost:1234', 'file' : '/tmp/bla'})
################
#some other mocking here, not relevant, I think
################
self.m.ReplayAll()
#now let's test
check_es_docs.main()
#verify and cleanup
self.m.VerifyAll()
def test_main_doesWhatPrintAndExitSays_inNormalConditions(self):
self.m.StubOutWithMock(check_es_insert,"getArgs")
check_es_insert.getArgs(\
'Nagios plugin for checking the total number of documents stored in Elasticsearch')\
.AndReturn({ 'critical' : 7, 'warning' : 5, 'address' : 'myhost:1234', 'file' : '/tmp/bla'})
################
#some other mocking here, not relevant, I think
################
self.m.ReplayAll()
#now let's test
check_es_docs.main()
#verify and clean up
self.m.VerifyAll()
self.m.ResetAll()
You can also use mox.MoxTestBase, which sets up self.mox and calls VerifyAll() on tearDown.
class ClassTestTest(mox.MoxTestBase):
def test():
m = self.mox.CreateMockAnything()
m.something()
self.mox.ReplayAll()
m.something() # If this line is removed the test will fail