ImportError: No module named 'code.helper' - python

This is probably a question that has been asked multiple times, but I couldn't find a post with the answer I am looking for.
This is my structure:
/myproject
--/code
--/__init__.py
--/helper.py
--/tests
--/test_helper.py
--/docs
code/helper.py
def testFunction(x)
return x + 1
test/test_helper.py
import unittest
from code.helper import testFunction
class MyTest(unittest.TestCase):
def test(self):
self.assertEqual(testFunction(3), 4)
Whenever I run 'python3 -m unittest test_helper.py' from ~/home/user/Projects/myproject/tests - I get the error:
ImportError: No module named 'code.helper'; 'code' is not a package
I am not receiving any syntax errors.

You don't have myproject in your Python path. It works when the current directory is myproject, because the current directory is always on the Python path. When you change to tests, though, Python no longer knows where to find code.
192% pwd
/Users/chepner/myproject
192% python3 -m unittest tests/test_helper.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
192% cd tests
192% pwd
/Users/chepner/myproject/tests
192% python3 -m unittest test_helper.py
E
======================================================================
ERROR: test_helper (unittest.loader._FailedTest)
----------------------------------------------------------------------
ImportError: Failed to import test module: test_helper
Traceback (most recent call last):
File "/usr/local/Cellar/python/3.6.4_4/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/loader.py", line 153, in loadTestsFromName
module = __import__(module_name)
File "/Users/chepner/myproject/tests/test_helper.py", line 2, in <module>
from code.helper import testFunction
ModuleNotFoundError: No module named 'code.helper'; 'code' is not a package
----------------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (errors=1)
The simple fix is, don't run the tests from the tests directory! Another solution, though, is to add myproject to the path before running the tests:
% PYTHONPATH=.. python3 -m unittest test_helper.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
You can add anything to PYTHONPATH that will correctly resolve to myproject; I just used the trivial relative path .. here, but an absolute path like PYTHONPATH=/Users/chepner/myproject would work, too.

Related

Name 'pytest' is not defined. how to run testpy?

I have installed python with conda.
pytest --version
This is pytest version 3.0.5, imported from /home/fabiano/anaconda3/lib/python3.6/site-packages/pytest.py
My test script
def tc1():
given="49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d"
expected=b"SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t"
assert base64.b64encode(bytes.fromhex(given)) == expected
I have imported pytest
import pytest
I am trying some stuff with pytest.But when I try from Python shell,I have problems like this
testset.py
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'testset' is not defined
In my shell
pytest
<module 'pytest' from '/home/fabiano/anaconda3/lib/python3.6/site-packages/pytest.py'>
Where should I save testset.py file?
pytest does test discovery. The basic steps are well listed in their documentation
Name the file containing the test test_*.py or *_test.py.
Name the test functions in those files def test_*
For you test, place the following code in the file test_set.py:
import base64
def test_tc1():
given="49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d"
expected=b"SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t"
assert base64.b64encode(bytes.fromhex(given)) == expected
Navigate to the directory containing the file test_set.py and execute the pytest command:
pytest
Expected output:
user#pc:/tmp/test_dir $ pytest .
============================= test session starts ==============================
platform linux -- Python 3.5.2+, pytest-3.0.3, py-1.4.31, pluggy-0.4.0
rootdir: /tmp/test_dir , inifile: collected 1 items
test_set.py .
=========================== 1 passed in 0.01 seconds ===========================

How to run a single test case in nose2

I'd like to run a single test contained in a subclass of unittest.TestCase using nose2 following How to run specific test in Nose2, but it doesn't seem to work for me. I'm using the following example script, which I've named mickey_mouse_test.py:
import unittest
class TestMickeyMouse(unittest.TestCase):
def test_1plus1is2(self):
self.assertTrue(1+1 == 2)
def test_to_uppercase(self):
self.assertEqual("hello".upper(), "HELLO")
if __name__ == "__main__":
unittest.main()
If I run nose2 mickey_mouse_test in the same directory, it runs all the tests in the module:
kurt#kurt-ThinkPad:~/Documents/Scratch$ nose2 mickey_mouse_test
..
----------------------------------------------------------------------
Ran 2 tests in 0.001s
OK
However, if I try to run just test_to_uppercase like so I get an error:
kurt#kurt-ThinkPad:~/Documents/Scratch$ nose2 mickey_mouse_test.test_to_uppercase
E
======================================================================
ERROR: mickey_mouse_test.test_to_uppercase (nose2.loader.LoadTestsFailure)
----------------------------------------------------------------------
AttributeError: module 'mickey_mouse_test' has no attribute 'test_to_uppercase'
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (errors=1)
If I use the -s option I still get an error, albeit a different one:
kurt#kurt-ThinkPad:~/Documents/Scratch$ nose2 -s mickey_mouse_test.test_to_uppercase
E
======================================================================
ERROR: mickey_mouse_test.test_to_uppercase (nose2.loader.LoadTestsFailure)
----------------------------------------------------------------------
OSError: /home/kurt/Documents/Scratch/mickey_mouse_test.test_to_uppercase is not a directory
----------------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (errors=1)
I've also tried reading the "Specifying tests to run" section in http://nose2.readthedocs.io/en/latest/usage.html, in which it is stated that the 'Python object part' should be a 'dotted name'. I don't see why in this case, mickey_mouse_test.test_to_uppercase is not a 'dotted name'. Any ideas why this is not working?
Here is a way to run just test_to_uppercase without using nose2 (following Running single test from unittest.TestCase via command line):
kurt#kurt-ThinkPad:~/Documents/Scratch$ python mickey_mouse_test.py TestMickeyMouse.test_to_uppercase
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK

django 1.9 tests: Able to test the whole project but fails to run individual tests

I have a django 1.9 app with tests that looks like this:
these test_*** files contain django.test.TestCase classes, as usual.
When I test the whole project with
python manage.py test --keepdb
everything works perfectly, all tests are found and ran.
Using existing test database for alias 'default'...
....................................................
----------------------------------------------------------------------
Ran 38 tests in 12.214s
OK
However, when I try to run an individual test, like so
python manage.py test bots.NodeTreeWalkerTests.test_regex_questions --keepdb
it fails:
Using existing test database for alias 'default'...
E
======================================================================
ERROR: NodeTreeWalkerTests (unittest.loader._FailedTest)
----------------------------------------------------------------------
ImportError: Failed to import test module: NodeTreeWalkerTests
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/unittest/loader.py", line 153, in loadTestsFromName
module = __import__(module_name)
ImportError: No module named 'bots.NodeTreeWalkerTests'
It worked before, but I renamed my project, and now it doesn't work.
It looks like I've messed up some environment variables, but I changed all old name instances to the new name, and the project itself works perfectly, but this one particular issue remains.
I tried importing test cases to the tests.__init__ file
from bots.tests.test_node_tree_walker import NodeTreeWalkerTests
but it didn't help.
What am I missing?
UPDATE:
Thanks to Izkata's comment I got the test to work with a more detailed path
python manage.py test bots.tests.test_node_tree_walker.NodeTreeWalkerTests.test_regex_questions
But why does Pycharm keep suggesting me the wrong path?

Get staus if python tests all passed

I'm trying to write a Ruby script to execute all Python tests in a directory.
Here is the main part of the script:
system("python #{solution}/tests.py")
Is there a way to somehow understand if the tests have passed and to show output only for the ones that failed (or whatever else)? I just want to be able to tell for each test if it passed or not. (If not possible with Ruby, I'm open for solutions with Python, too)
The tests all look like this one:
import unittest
from solution import my_function
class MyFunctionTest(unittest.TestCase):
def test_my_function(self):
self.assertEqual(42, my_function(42))
if __name__ == '__main__':
unittest.main()
Thanks very much in advance! :)
You can print the output for failing tests with nosetests, which runs them all and condenses the passing tests:
$ nosetests
.............
----------------------------------------------------------------------
Ran 13 tests in 0.015s
OK
Adding a failing test:
$ nosetests
F.............
======================================================================
FAIL: test_failed (x32.tests.failing_test.FailingTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/leigh/Projects/x32/x32/tests/failing_test.py", line 5, in test_failed
self.assertEqual(1, 2)
AssertionError: 1 != 2
----------------------------------------------------------------------
Ran 14 tests in 0.013s
FAILED (failures=1)
There's a guide for nose here, as well: https://nose.readthedocs.org/en/latest/
Alternatively you can go to the parent directory and run something like python -m pytest . to execute the tests, however this will tell you which ones pass as well.

Python: Conditional variables based on whether nosetest is running

I'm running nosetests which have a setup function that needs to load a different database than the production database. The ORM I'm using is peewee which requires that the database for a model is set in the definition.
So I need to set a conditional variable but I don't know what condition to use in order to check if nosetest is running the file.
I read on Stack Overflow that you can check for nose in sys.modules but I was wondering if there is a more exact way to check if nose is running.
Perhaps examining sys.argv[0] to see what command is running?
Examining sys.argv might work, but you can execute nose either with nosetests or python -m nose, which obviously will give you a different result.
I think the more robust way is to inspect the stack and see if the code is being called through a package called nose.
Example code:
import inspect
import unittest
def is_called_by_nose():
stack = inspect.stack()
return any(x[0].f_globals['__name__'].startswith('nose.') for x in stack)
class TestFoo(unittest.TestCase):
def test_foo(self):
self.assertTrue(is_called_by_nose())
Example usage:
$ python -m nose test_caller
.
----------------------------------------------------------------------
Ran 1 test in 0.009s
OK
$ nosetests test_caller
.
----------------------------------------------------------------------
Ran 1 test in 0.009s
OK
$ python -m unittest test_caller
F
======================================================================
FAIL: test_foo (test_caller.TestFoo)
----------------------------------------------------------------------
Traceback (most recent call last):
File "test_caller.py", line 14, in test_foo
self.assertTrue(is_called_by_nose())
AssertionError: False is not true
----------------------------------------------------------------------
Ran 1 test in 0.004s
FAILED (failures=1)

Categories

Resources