I have following code:
def tearDown(self):
e_type, e_value, tb = sys.exc_info()
if e_type is not None:
logging.error((traceback.format_exception(e_type, e_value, tb)))
when I used Python 2.7 everything works fine, but after upgrade to version 3.6 it doesn't work anymore:
For example I have created some example for testing and I expect error.
def test_create_new_user_without_all_fields1(self):
self.assertEqual('USER_1', 'USER_2')
logging.info('test_create_new_user_without_all_fields1: Passed')
Result in console:
======================================================================
FAIL: test_create_new_user_without_all_fields1 (test_testExample.BaseTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Dev\git\CST\tests\test_testExample.py", line 16, in test_create_new_user_without_all_fields1
self.assertEqual('USER_1', 'USER_2')
AssertionError: 'USER_1' != 'USER_2'
- USER_1
+ USER_2
? +
lets add small print to tearDown:
print (sys.exc_info())
Result:
(None, None, None)
As can we see there is no exceptions anymore, but should be. How to fix this problem ?
e_type, e_value, tb = self._outcome.errors[1][1]
logging.error(''.join(traceback.format_exception(e_type, e_value, tb)))
Related
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?
Could you help me understand what is going on here. The question is about the error in the traceback. The failure is just as the illustration. And what I would like to illustrate that the function works.
Well, I was told that 2 positional arguments: 'view_instance' and 'address' are missing.
But the method really has taken those 2 positional arguments and worked happily till its logical end. In the interactive playing I show that I can catch the arguments transmitted.
Why does error appear? Thank you in advance for your help.
ADDED LATER:
Well, this seems to be because of the 'test_' beginning of the function.
Without "test" it works (def anonymous_user_redirected_to_login_page(self, view_instance, address):).
/photoarchive/general/tests.py
class GeneralTest(TestCase):
def test_anonymous_user_redirected_to_login_page(self, view_instance, address):
pdb.set_trace()
request = RequestFactory().get(address)
request.user = AnonymousUser()
response = view_instance(request)
self.assertEqual(response.status_code, 302)
self.assertEqual(response['location'], '/accounts/login/')
def test_anonymous_user_from_home_page_redirected_to_login_page(self):
view_instance = HomePageView.as_view()
address = '/'
self.test_anonymous_user_redirected_to_login_page(view_instance, address)
Traceback
(photoarchive) michael#michael:~/workspace/photoarchive/photoarchive$ python manage.py test general
Creating test database for alias 'default'...
FE
======================================================================
ERROR: test_anonymous_user_redirected_to_login_page (general.tests.GeneralTest)
----------------------------------------------------------------------
TypeError: test_anonymous_user_redirected_to_login_page() missing 2 required positional arguments: 'view_instance' and 'address'
======================================================================
FAIL: test_anonymous_user_from_home_page_redirected_to_login_page (general.tests.GeneralTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/michael/workspace/photoarchive/photoarchive/general/tests.py", line 29, in test_anonymous_user_from_home_page_redirected_to_login_page
self.test_anonymous_user_redirected_to_login_page(view_instance, address)
File "/home/michael/workspace/photoarchive/photoarchive/general/tests.py", line 23, in test_anonymous_user_redirected_to_login_page
self.assertEqual(response.status_code, 302)
AssertionError: 200 != 302
----------------------------------------------------------------------
Ran 2 tests in 0.002s
FAILED (failures=1, errors=1)
Destroying test database for alias 'default'...
Interactive playing:
(photoarchive) michael#michael:~/workspace/photoarchive/photoarchive$ python manage.py test general
Creating test database for alias 'default'...
> /home/michael/workspace/photoarchive/photoarchive/general/tests.py(20)test_anonymous_user_redirected_to_login_page()
-> request = RequestFactory().get(address)
(Pdb) view_instance
<function HomePageView at 0x7faa0f76fea0>
(Pdb) address
'/'
(Pdb)
test_anonymous_user_redirected_to_login_page() method is treated by unittest framework as a test method, because its name starts with test. The framework tries to execute it, but is not passing any arguments to it (test methods don't normally take any arguments). However, the method requires them, hence the error.
If this method is only a helper method to be called from the other method, name it so that it doesn't start with test, e.g. _test_anonymous_user_redirected_to_login_page().
Note that the traceback is not related to this problem. The traceback simply shows where the other test method failed at an assertion. That is, the other test method runs correctly (both in unittest run and in your interactive session).
I have Python 2.7.5 on my system python --version
I have a basic script that tries to verify something and assert if false. Here is the simple test I created that is failing.
Note Early on Asserts (pre 2.7) works fine.
import unittest
class TestSuite (unittest.TestCase):
def test002_last_Chat(self):
logger.info("This will select the chat with the user who we cleared. .")
a.selectMenu('Start a Chat')
self.assertEqual("im", "im") #This assert works fine
self.assertIn ("a", "apple") #FAILS
self.assertIn ("a", "pple") #FAILS
logger.info ("test01")\
if __name__ == '__main__':
logger.info("Running test: "+scriptName)
a = IPHONE()
b = BROWSER()
c = SAWS()
myTest = TestSuiteRunner(TestSuite, scriptName, testDescription, device=device)
myTest.runtest()
I get this error when I run it
Test complete (ERROR): test002_last_Chat (__main__.TestSuite)
(<type 'exceptions.AttributeError'>, AttributeError("'TestSuite' object has no attribute 'assertIn'",), <traceback object at 0x3>)
Traceback (most recent call last):
File "/Users/drlazor/Documents/AIM/6-17/oscar/qa/clients/TRAVOLTA/scripts_iphone/iphoneAIM_close.sikuli/iphoneAIM_close.py", line 194, in test002_last_Chat
self.assertIn ("a", "apple")
AttributeError: 'TestSuite' object has no attribute 'assertIn'
I am using this documentation http://docs.python.org/2/library/unittest.html#assert-methods as a guide.
There seems to be an issue with assertIn in some versions of Python. Here's an alternative that should work:
a = 'a'
apple = 'apple'
self.assertTrue(a in apple, '{} not in {}'.format(a, apple))
I'm using ajax and django for dynamically populate a combo box. ajax component works really fine and it parse the data to the view but int the view, when i'm using the spiting function it gives me a exception called "Value Error:need more than 1 value to unpack ". can anyone helps me to figure out the error :) :)
code:
def dropdownPopulate(request):
if request.method=='POST' :
key = request.POST['id']
else:
key=""
level, tree_id=key.split(",")
next_nodes=Structure.objects.filter(tree_id=key[tree_id]).filter(level=key[level])
context={'name':next_nodes}
return render_to_response('renderAjax.html',context)
This is because s.split(',') is returning list of length 1:
level, tree_id = key.split(',')
Make sure it return list of length 2:
parts = key.split(',')
if len(parts) == 2:
level, tree_id = parts
elif len(parts) == 1:
level = parts[0]
tree_id = None
else:
# do something
level = tree_id = None
pass
The apply filter like this:
next_nodes = Structure.objects.all()
if level:
next_nodes = next_nodes.filter(level=level)
if tree_id:
next_nodes = next_nodes.filter(tree_id=tree_id)
Probably error occurs at this line:
level, tree_id=key.split(",")
It is needed to handle the situation, when key will not have ",". Or maybe it will have more than one ",".
Look at your code:
if request.method=='POST' :
key = request.POST['id']
else:
key=""
It is possible, that key will be a blank string.
Here are examples, when error can occur:
1.
>>> key = ""
>>> level, tree_id=key.split(",")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: need more than 1 value to unpack
2.
>>> key = "a,b,c"
>>> level, tree_id=key.split(",")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack
Only this will be fine (when it is only one ","):
>>> key = "a,b"
>>> level, tree_id=key.split(",")
>>>
You have multiple problems.
level, tree_id=key.split(",")
This will fail, as key may not have ,, so split will not return 2 values.
next_nodes=Structure.objects.filter(tree_id=key[tree_id]).filter(level=key[level])
Here you are accessing key as dict, which is incorrect as it is string.
import sys
def Hello(name):
name = name + '!!!'
print 'Hello' , name
def main():
Hello(sys.argv[1])
if __name__ == '__main__':
main()
Here is the error
Traceback (most recent call last):
File "D:\pythonPractice\firstPython.py", line 13, in <module>
main()
File "D:\pythonPractice\firstPython.py", line 9, in main
Hello(sys.argv[1])
IndexError: list index out of range
I have also tried sys.argv[2] but error remains
First things first, I think the code you originally posted (with Hello(sys.argv[0])) is not what you actually have. It doesn't match the error, which states sys.argv[1], so what you probably have is:
def main():
Hello(sys.argv[1])
As to the error then, it's because you haven't provided an argument when running. You need to do so, such that sys.argv[1] exists:
python helloprog Pax
You would find a more robust main as:
def main():
if len(sys.argv) < 2:
Hello("whoever you are")
else:
Hello(sys.argv[1])
which will detect when you haven't provided an argument, and use a suitable default rather than raising an exception.
Have you used
sys.argv[0]
Since this returns a list , you may not have elements >1