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

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.

Related

KeyError if I change constructor variable names

I'm going crazy trying to perform simple editing while creating a Python class constructor. I can create the simple class and constructor variable but once I try to change the names of the variable I get a KeyError.
The class is below:
class Collect:
def __init__(self, **kwargs):
self.foo = kwargs["foo"]
And the script where I instantiate the class and print out its attributes is below:
import mapper as m
payload = m.Collect(foo="Hello")
print(payload.foo)
Now this works just fine, but if I change "foo" to "bar" I get a KeyError Like below:
class Collect:
def __init__(self, **kwargs):
self.bar = kwargs["bar"]
and then running:
import mapper as m
payload = m.Collect(bar="Hello")
print(payload.bar)
will throw the following error:
Traceback (most recent call last): File "<stdin>", line 1, in
<module> File
"/path/to/mapper.py",
line 8, in __init__
self.bar = kwargs["bar"] KeyError: 'foo'
And the print function will throw the error below:
Traceback (most recent call last): File "<stdin>", line 1, in
<module> AttributeError: 'Collect' object has no attribute 'bar'
The weird thing is that if I hit save and then close VSCode and reopen, the new class with bar will work just fine. And, also even if I don't close VSCode the class will instantiate and the print statement will run just fine when I switch to Debug mode and run it. But when I try to highlight it and run a selection it throws that error.
How can I just test if the code works using the run selection operations and not relying on running in debug mode with breakpoints or having to close and reopen VSCode?
The solution was to reload my Python session. The VSCode reload extension makes this easy.

Mocking an entire class

Long story short, I'm perfectly able to mock class method, when it's just that method that's replaced by mock object, but I'm unable to mock that method when I'm trying to replace the whole class by the mock object
The #mock.patch.object successfully mocks the scan method but #mock.patch fails to do so. I've followed the example at
https://docs.python.org/3/library/unittest.mock.html#unittest.mock.patch
but apparently I'm doing something wrong.
I'm mocking the lexicon module in the same namespace in both cases (it's imported by import lexicon in the sentence_parser) but the mock_lexicon is lexicon.lexicon check fails
#!python
import sys;
sys.path.append('D:\python\lexicon');
import lexicon;
import sentence_parser;
import unittest2 as unittest;
import mock;
class ParserTestCases(unittest.TestCase) :
def setUp(self) :
self.Parser = sentence_parser.Parser();
#mock.patch('lexicon.lexicon')
def test_categorizedWordsAreAssigned_v1(self, mock_lexicon) :
print "mock is lexicon:";
print mock_lexicon is lexicon.lexicon + "\n";
instance = mock_lexicon.return_value;
instance.scan.return_value = "anything";
self.Parser.categorize_words_in_sentence("sentence");
instance.scan.assert_called_once_with("sentence");
#mock.patch.object(lexicon.lexicon, 'scan')
def test_categorizedWordsAreAssigned_v2(self, mock_scan) :
mock_scan.return_value = "anything";
self.Parser.categorize_words_in_sentence("sentence");
mock_scan.assert_called_once_with("sentence");
if (__name__ == '__main__') :
unittest.main()
Output :
mock is lexicon:
False
======================================================================
FAIL: test_categorizedWordsAreAssigned_v1 (__main__.ParserTestCases)
----------------------------------------------------------------------
Traceback (most recent call last):
File "D:\python\get_img\getImage_env\lib\site-packages\mock\mock.py", line 1305, in patched
return func(*args, **keywargs)
File "./test_sentence_parser.py", line 26, in test_categorizedWordsAreAssigned_v1
instance.scan.assert_called_once_with("sentence");
File "D:\python\get_img\getImage_env\lib\site-packages\mock\mock.py", line 947, in assert_called_once_with
raise AssertionError(msg)
AssertionError: Expected 'scan' to be called once. Called 0 times.
----------------------------------------------------------------------
Ran 2 tests in 0.009s
FAILED (failures=1)
EDIT :
To clarify, the Parser is defined as follows
#!python
import sys;
sys.path.append('D:\python\lexicon');
import lexicon;
class Parser(object) :
my_lexicon = lexicon.lexicon()
def __init__(self) :
self.categorized_words = ['test'];
def categorize_words_in_sentence(self, sentence) :
self.categorized_words = self.my_lexicon.scan(sentence);
if (__name__ == '__main__') :
instance = Parser();
instance.categorize_words_in_sentence("bear");
print instance.categorized_words;
What is real relevant here is how categorize_words_in_sentence Parser's method use lexicon. But first of all we should remove the noise:
print mock_lexicon is lexicon.lexicon + "\n"
Is what can lead us to the wrong direction: try to replace it by
self.assertIs(mock_lexicon, lexicon.lexicon)
and you will understand that you are printing False because mock_lexicon is not lexicon.lexicon + "\n" but just lexicon.lexicon.
Now I cannot tell you why the first test doesn't work because the answer is in categorize_words_in_sentence method or more probably in sentence_parser module where I can guess you can have something like
from lexicon import lexicon
In both case take a look to Where to Patch documentation that can enlighten you on what can be the cause and what you really need to patch in your case.
The second version works just because you are patching the object and not the reference (that should be different).
Finally the more concise and general version can be:
#mock.patch('lexicon.lexicon.scan', return_value="anything")
def test_categorizedWordsAreAssigned_v3(self, mock_scan) :
self.Parser.categorize_words_in_sentence("sentence")
mock_scan.assert_called_once_with("sentence")
One more thing: remove unittest2 at least you're not using python 2.4 and you are interested on backported unittest features.
[EDIT]
Now I can stop to guess and point to you why the first version doesn't work and will never work:
class Parser(object) :
my_lexicon = lexicon.lexicon()
Parser.my_lexicon attribute is evaluated at the load time. That means when you import sentence_parser a lexicon is created and the reference associated to Parser.my_lexicon. When you patch lexicon.lexicon you leave this reference untouched and your parser object still use the original reference created when is imported.
What you can do is to patch the reference in Parser class by
#patch("sentence_parser.Parser.my_lexicon")
You can use create_autospect if you want give to your mock the same lexicon's signature.
#patch("sentence_parser.Parser.my_lexicon", create_autospec("lexicon.lexicon", instance=True))

NameError: name 'word' is not defined

I'm trying to make a mixWord function and I'm getting an error saying
NameError: name 'word' is not defined
What am I missing from here?
def mixWord(word):
characterList = list(word);
print characterList
import random;
random.shuffle(characterList);
print characterList;
shuffledWord = ''.join(characterList);
print shuffledWord;
Traceback (most recent call last):
File "", line 1, in
mixWord (word)
NameError: name 'word' is not defined
The problem is PEBKAC - exactly what form, is for you to find out.
That is, the code executed is not the same as the code posted; the posted code works as expected:
def mixWord(word):
characterList = list(word);
print characterList
import random;
random.shuffle(characterList);
print characterList;
shuffledWord = ''.join(characterList);
print shuffledWord;
mixWord("PEBKAC")
So, find out why:
Has the file been saved?
Has the file been saved to the correct location?
Is the file from the correct location being run?
Is the error from different code entirely?
Also try running the code directly from an IDLE buffer as that should be immune to the previous potential issue(s).
After resolving the issue, consider updating the code to not using semicolons as they are not required here and it is un-Pythonic.
I think the problem is that you are calling mixWord(word) without defining any word variable.

Python : NameError: global name 'GetText' is not defined

I have been stuck with this error for a couple of hours now. Not sure what is wrong. Below is the piece of code
NameError: global name 'GetText' is not defined
class BaseScreen(object):
def GetTextFromScreen(self, x, y, a, b, noofrows = 0):
count = 0
message = ""
while (count < noofrows):
line = Region(self.screen.x + x, self.screen.y + y + (count * 20), a, b)
message = message + "\n" + line.text()
count += 1
return message
class HomeScreen(BaseScreen):
def GetSearchResults(self):
if self.screen.exists("Noitemsfound.png"):
return 'No Items Found'
else:
return self.GetTextFromScreen(36, 274, 680, 20, 16)
class HomeTests(unittest.TestCase):
def test_001S(self):
Home = HomeScreen()
Home.ResetSearchCriteria()
Home.Search("0009", "Key")
self.assertTrue("0009" in Home.GetSearchResults(), "Key was not returned")
Basescreen class has all the reusable methods applicable across different screens.
Homescreen inherits Basescreen.
In HomeTests test case class, the last step is to Home.GetSearchResults() which in turn calls a base class method and the error.
Note:
I have another screenclass and testcaseclass doing the same which works without issues.
I have checked all the importing statements and is ok
'GetText' in the error message is the name of method initially after which i changed it to GetTextFromScreen
Error message is still pointing to a line 88 in code which is not there any more. Module import/reloading issue?
Try clearing out your *.pyc files (or __pycache__ if using 3+).
You asked:
Error message is still pointing to a line 88 in code which is not there any more. Module import/reloading issue?
Yes. The traceback (error messages) will show the current (newest saved) file, even if you haven't run it yet. You must reload/reimport to get the new file.
The discrepancy comes from the fact that traceback printouts read from the script file (scriptname.py) saved on your drive. However, the program is run either from the module saved in memory, or sometimes from the .pyc file. If you fix an error by changing your script, and save it to your drive, then the same error will still occur if you don't reload it.
If you're running interactively for testing, you can use the reload function:
>>> import mymodule
>>> mymodule.somefunction()
Traceback (most recent call last):
File "mymodule.py", line 3, in somefunction
Here is a broken line
OhNoError: Problem with your file
Now, you fix the error and save mymodule.py, return to your interactive session, but you still get the error, but the traceback shows the fixed line
>>> mymodule.somefunction()
Traceback (most recent call last):
File "mymodule.py", line 3, in somefunction
Here is the fixed line
OhNoError: Problem with your file
So you have to reload the module:
>>> reload(mymodule)
<module 'mymodule' from '/path/to/mymodule.py'>
>>> mymodule.somefunction()
Success!

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