Import unittest error

This is my first time I do unit testing and I try to run simple code ...

import random
import unittest

class TestSequenceFunctions(unittest.TestCase):

    def setUp(self):
        self.seq = range(10)

    def test_shuffle(self):
        # make sure the shuffled sequence does not lose any elements
        random.shuffle(self.seq)
        self.seq.sort()
        self.assertEqual(self.seq, range(10))

        # should raise an exception for an immutable sequence
        self.assertRaises(TypeError, random.shuffle, (1,2,3))

    def test_choice(self):
        element = random.choice(self.seq)
        self.assertTrue(element in self.seq)

    def test_sample(self):
        with self.assertRaises(ValueError):
            random.sample(self.seq, 20)
        for element in random.sample(self.seq, 5):
            self.assertTrue(element in self.seq)

suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)
unittest.TextTestRunner(verbosity=2).run(suite)

then i get an error message ...

Traceback (most recent call last):
  File "/Users/s66/Desktop/unittest.py", line 2, in <module>
    import unittest
  File "/Users/s66/Desktop/unittest.py", line 4, in <module>
    class TestSequenceFunctions(unittest.TestCase):
AttributeError: 'module' object has no attribute 'TestCase'
>>> 

How to fix it?

+3
source share
3 answers

This is because your script name is called unittest.py. The statement import unittestimports your script, not the unittest module, so an error with a nonexistent attribute TestCase.

See the docs for Search module path for more details . In short, when importing, the built-in modules are executed first, followed by the directories listed in sys.path. This usually starts with the location of the current script, and then PYTHONPATHTHEN, and then the default module directory

, unittest , script ( ), .

?

script.

+16

, script, unittest.py?

, .

test_choice (__main__.TestSequenceFunctions) ... ok
test_sample (__main__.TestSequenceFunctions) ... ERROR
test_shuffle (__main__.TestSequenceFunctions) ... ok

======================================================================
ERROR: test_sample (__main__.TestSequenceFunctions)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test.py", line 23, in test_sample
    with self.assertRaises(ValueError):
TypeError: failUnlessRaises() takes at least 3 arguments (2 given)

----------------------------------------------------------------------
Ran 3 tests in 0.000s

FAILED (errors=1)
0

, , stackoverflow Google , .

django 1.5 django 1.10, "import unittest" .

- app/tests/ init.py, ( django 1.5, . ).

, , init.py, .

Hope this helps some people as I have lost 30 to 1 hours on this issue.

0
source

All Articles