Python unit test - NameError: name 'upper' is not defined [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
Using Python 3.x. When running the test case for the following code, I get the error - NameError: name 'upper' is not defined. I am attaching the file to test, the File_P_third file where is the code, and the unit test file test_upper.
File File_P_third:
def upper_text(text):
return text.upper()
File test_upper:
import unittest
import File_P_third
class TestUpper(unittest.TestCase):
"""docstring for ClassName"""
def test_one_word(self):
text = 'hello!'
result = upper.upper_text(text)
self.assertEqual(result, 'HELLO!')
if __name__ == '__main__':
unittest.main()
My cmd`s exit text:
D:\Дохуя программист\Projects>python test_upper.py
E
======================================================================
ERROR: test_one_word (__main__.TestUpper)
----------------------------------------------------------------------
Traceback (most recent call last):
File "test_upper.py", line 9, in test_one_word
result = upper.upper_text(text)
NameError: name 'upper' is not defined
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (errors=1)
All files is in one directory and I still cant understand why is doesnt work. Can`t search the same problem in internet((

If you're trying to transform 'hello' to upper case, the function to do so in python is string.upper()
i takes no parameter see below:
test='hello'
up=test.upper()
print(up)
# prints HELLO

Replace import File_P_third with from File_P_third import upper_text. Call your function this way result = upper_text(text). Also make sure, both files File_P_third.py and test_upper.py are in the same directory.
Below you'll find the complete code for your file File_P_third.py:
import unittest
from File_P_third import upper_text
class TestUpper(unittest.TestCase):
"""docstring for ClassName"""
def test_one_word(self):
text = 'hello!'
result = upper_text(text)
self.assertEqual(result, 'HELLO!')
if __name__ == '__main__':
unittest.main()

Related

traceback not full when passing to next fucntion [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
Basically I have something like this:
import traceback
def function1():
try:
temp = None
temp = int(temp)
except:
pass
Which obviously rises error (due to casting NoneType to int), then there is a second method that is called only if previous one had error:
def function2():
# do something
traceback.print_exc()
Though it doesn't print full traceback as it would do if invoked in the except clause, it just says:
NoneType: None
Where does this change come from? And is there any way to still print a full stack trace?
If you call like this, the error context, the traceback does not longer exists as you went away from it
function1()
function2()
You need to call function2 from the except block, to keep track of the traceback
import traceback
def function1():
try:
temp = None
temp = int(temp)
except:
function2()
def function2():
traceback.print_exc()
if __name__ == '__main__':
function1()
Giving
Traceback (most recent call last):
File "C:\Users\...\test_4.py", line 7, in function1
temp = int(temp)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'

Calling unittest.main() in PyCharm - AtrributeError: module '__main__' has no atrribute

I think this is more a PyCharm question than unittest question, but I'm studying testing from a book and this example is failing me as written. I'm running PyCharm 2016.3.2 and Python 3.6
import unittest
from name_function import get_formatted_name
class NamesTestCase(unittest.TestCase):
"""Tests for 'name_function.py'."""
def test_first_last_name(self):
"""Do names like 'Janis Joplin' work?"""
formatted_name = get_formatted_name('janis', 'joplin')
self.assertEqual(formatted_name, 'Janis Joplin')
# In book, it's just the unittest.main() , which does not work...
# So in PyCharm __name__ doesn't equal __main__ ... not sure why
# if __name__ == '__main__':
unittest.main()
Here is name_function.py:
def get_formatted_name(first, last):
"""Generate a neatly formatted full name."""
full_name = first + " " + last
return full_name.title()
If I run it as written, I get the following error:
EE
======================================================================
ERROR: test_name_function (unittest.loader._FailedTest)
----------------------------------------------------------------------
AttributeError: module '__main__' has no attribute 'test_name_function'
======================================================================
ERROR: true (unittest.loader._FailedTest)
----------------------------------------------------------------------
AttributeError: module '__main__' has no attribute 'true'
----------------------------------------------------------------------
Ran 2 tests in 0.000s
If I let the "if" statement run (or just delete the call to unittest.main()) then it works properly, with no main() call at all.
This is all in a test_name_function.py. So it seems like when running this one file (and importing name_function.py) that PyCharm does not consider this one file to be __main__ ? Is PyCharm doing something else behind the scenes?
I'm new to Python and PyCharm and trying to get my head around the structure and environment. Thanks very much guys.
You can use this method to figure it out.
suite = unittest.defaultTestLoader.loadTestsFromTestCase(NamesTestCase)
unittest.TextTestRunner().run(suite)

Exception message best practices [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 1 year ago.
Improve this question
I've written a small production-level Flask application in Python with standard exception handling. Most of the time I'm just logging the exception message and it looks like this
try:
#Do something
except Exception, e:
logger.error('Exception in LoadValidationDocs in main.py : %s' % str(e.args))
return None
I was wondering if I should keep all such error messages in a separate strings.py file like
standard_exception_message = 'Exception in %s in %s, Exception Args : %s'
and get function and module name at run time like
import inspect
function_name = inspect.stack()[0][3]
file_name = os.path.basename(__file__)
logger.error(strings. standard_exception_message % (function_name, file_name, str(e.args)))
I just want to know whether it's necessary to do that and is it even the correct way of doing it considering my current scenario.
You can use logging.exception instead of logging.error. It will take care of looking for the function, module name etc. for you in a formatted way:
import logging
try:
# Do something that will fail
x = 1 / 0
except Exception as e:
logging.exception("This is my message when an error happens here.")
It gives:
ERROR:root:This is my message when an error happens here.
Traceback (most recent call last):
File "question39724934.py", line 5, in compute
x = 1 / 0
ZeroDivisionError: division by zero

name 'self' is not defined when doing an unittest?

Edit
So I did try again, with a new file called test2.py and it works. I packaged repoman , and test.py is in the src folder. I modified test.py after I created and installed my repoman egg. I think that's the problem. But thanks for the help. Do you guys think that's the exact reason?
import unittest
import requests
from repoman.core import ultraman, supported
from repoman.ext import writefile,locate_repo
class TestWriteFile(unittest.TestCase):
def setUp(self):
self.username = 'dummy'
self.password = 'dummy'
self.remote = 'http://192.168.1.138:6666/scm/hg/NCL'
def test_scm_permission(self):
"""
Test SCM login.
"""
r = requests.get("http://192.168.1.138:6666/scm/", auth=(self.username, self.password))
self.assertTrue(r.ok)
if __name__ == '__main__':
unittest.main()
Running python test.py I get this error:
Traceback (most recent call last):
File "test.py", line 7, in <module>
class TestWriteFile(unittest.TestCase):
File "test.py", line 19, in TestWriteFile
self.assertTrue(r.ok)
NameError: name 'self' is not defined
I don't think I need to overwrite __init__ function, do I? What's causing this? Why is self not defined? I already declared my superclass unittest.TestCase
Thanks.
I basically learned it from the official sample: Unittest - Basic Example
I'm not sure where the problem is coming from -- whether it's a copying error or the wrong test.py is being executed [update: or some mixed tabs-and-spaces issue, I can never figure out when those get flagged and when they don't] -- but the root cause is almost certainly an indentation error.
Note that the error message is
NameError: name 'self' is not defined
and not
NameError: global name 'self' is not defined
which #Rik Poggi got. This is exactly what happens if you move the self.assertTrue one level in/up:
~/coding$ cat test_good_indentation.py
import unittest
class TestWriteFile(unittest.TestCase):
def test(self):
"""
Doc goes here.
"""
self.assertTrue(1)
if __name__ == '__main__':
unittest.main()
~/coding$ python test_good_indentation.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
versus
~/coding$ cat test_bad_indentation.py
import unittest
class TestWriteFile(unittest.TestCase):
def test(self):
"""
Doc goes here.
"""
self.assertTrue(1)
if __name__ == '__main__':
unittest.main()
~/coding$ python test_bad_indentation.py
Traceback (most recent call last):
File "test_bad_indentation.py", line 3, in <module>
class TestWriteFile(unittest.TestCase):
File "test_bad_indentation.py", line 8, in TestWriteFile
self.assertTrue(1)
NameError: name 'self' is not defined
I don't think that what you showed is the actual code that get executed.
I and others belive that, for a couple of reasons:
If self.assertTrue(r.ok) fails then the line before will too. Therefore self.assertTrue(r.ok) won't execute. (as David Heffernan said)
And because your code looks fine.
I'd say that you probably made a typo of this kind:
def test_scm_permission(self):
^
|
and wrote something here that's not self
In some file that get executed instead of the one you're showing.
Take a look at this example:
# test.py
class MyClass:
def func(sel): # typo error here
self.name = 10
obj = MyClass()
obj.func()
And when I tried to run:
$ python3 test.py
Traceback (most recent call last):
File "test.py", line 8, in <module>
obj.func()
File "test.py", line 4, in func
self.name = 10
NameError: global name 'self' is not defined
Having a traceback similar to yours.
Note: Also if I'm not counting wrong self.assertTrue(r.ok) is on line 18, instead of line 19 (which is the number showed in your traceback).
This is a rewording of David Heffernan's comment.
The code you posted cannot be the cause of that traceback.
Consider these two lines from your code:
r = requests.get("http://192.168.1.138:6666/scm/", auth=(self.username, self.password))
self.assertTrue(r.ok)
The traceback says the error (NameError: name 'self' is not defined)
occurs on the second line (self.assertTrue(r.ok)). However, this cannot have been the case because the first line refers to self. If self were not defined, we would not get past the first line.
Therefore, the code you posted is not the code you ran.
This is an old question, but thought I'd add my two cents as it was not mentioned here. I agree with others that there is some type of spelling error in the original code. Look at this code carefully:
import unittest
import requests
class TestWriteFile(unittest.TestCase):
def setup(self):
self.username = 'dummy'
def test_scm_permission(self):
r = requests.get("http://192.168.1.138:6666/scm/", auth=(self.username, self.password))
self.assertTrue(r.ok)
The code appears okay at first glance (and lint tools will not complain); however, I wrote setup, instead of setUp (note the capital U). This causes self.username not to be defined in the test_scm_permission context, because python did not automatically call my mispelled function name. This is something else to check if you're running into this type of error, but are certain you've defined the class members correctly.
I had the same problem, but not with self. It was a regular variable, defined the line before the error occured.
It was apparently due to ... mixin tabs and spaces.
I replaced all tabs by 4 spaces, and the problem disappeared.
For some unspecified reason, instead of the traditional indentation error, I had this one.

UnitTest in Python [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
ValueError: no such test method in <class 'myapp.tests.SessionTestCase'>: runTest
import unittest
class BzTestSe(unittest.TestCase):
DEFAULTUSERNAME = 'username-a2'
DEFAULTPASSWORD = 'pass'
DEFAULTHOST = 'localhots'
def __init__(self,username=DEFAULTUSERNAME, password=DEFAULTPASSWORD, host=DEFAULTHOST):
super(unittest.TestCase,self).__init__()
self.username=username
self.password=password
self.host=host
class test_se_topwebsite(BztTestSe):
def setUp(self):
print "setup"
def test_test_se_topwebsite(self):
self.fail()
When I call the above class from another file,I get the following error. Please let me know where I am wrong.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "testsuite/test_se.py", line 10, in __init__
super(unittest.Testcase,self).__init__()
File "/usr/lib/python2.7/unittest/case.py", line 184, in __init__
(self.__class__, methodName))
ValueError: no such test method in <class 'testsuite.test_se.BztTestSe'>: runTest
Lets try and go back to something simple. In using unittest you have a couple of ways to execute your test cases but the simplest way is to have a main function in the file that contains your unittests.
For example:
import unittest
class TestSomething(unittest.TestCase):
def setUp(self):
self.message = "does this work"
def test_message_is_expected(self):
self.assertEquals("does this work", self.message)
if __name__ == '__main__':
unittest.main()
Note your test cases (classes) sub class unittest.TestCase, you then use a setUp method to set any state for your test cases, and finally you'll want some methods prefixed test_ ... which the test runner will execute.
If you saved the above file into lets say test_something.py and then in a console ran python test_something.py you'd see the results of the test output to the console.
If you can re cast your example into something a little clearer using this pattern rather than the inheritance hierarchy you've used you may be able to execute your tests.
I realise this is more of a comment than an answer but I can't yet make comments.

Categories

Resources