New to testing Python code, need help!

I do not do tests, but I would like to start. I have a few questions:

  • Can a module be used unittestfor this? As far as I understand, the module unittestwill run any method starting with test.
  • If I have a separate directory for tests (consider a directory with a name tests), how do I import the code I'm testing? Do I need to use a module imp? Here is the directory structure:

CSI /

Tests /

+3
source share
4 answers

Good to use unittest. This module will run methods starting with testfor classes that inherit from unittest.TestCase.

imp - . src :

import sys
sys.path.append('../src') # OnLinux  - use r'..\src' for Windows

.

PYTHONPATH.

(Windows) SET PYTHONPATH=path\to\module; python test.py

(Linux) PYTHONPATH=path/to/module; python test.py

unittest nose.

+4

Python - doctest, , , , , . .

+5

.

, , :

import sys, os, re, unittest

# Run all tests in t/

def regressionTest():
    path = os.path.abspath(os.path.dirname(sys.argv[0])) + '/t'
    files = os.listdir(path)
    test = re.compile("^t_.+\.py$", re.IGNORECASE)
    files = filter(test.search, files)
    filenameToModuleName = lambda f: 't.'+os.path.splitext(f)[0]
    moduleNames = map(filenameToModuleName, files)
    modules = map(__import__, moduleNames)
    modules = map(lambda name: sys.modules[name], moduleNames)
    load = unittest.defaultTestLoader.loadTestsFromModule
    return unittest.TestSuite(map(load, modules))

suite = regressionTest()

if __name__ == "__main__":
    unittest.TextTestRunner(verbosity=2).run(suite)

t, t_<something>.py.

Python, Dive Into Python .

+2

., Dive Into Python Python unittest. , .

I wrote a blog post describing my approach to importing modules for testing . Please note that it eliminates the disadvantage of the Vinay Sajip approach, which will not work if you call the testing module from anywhere except the directory in which it is located. The reader posted a good solution in the comments of my blog post.

S. Lott suggests a method that uses PYTHONPATHVinay in a message; I hope he talks about this.

+2
source

Source: https://habr.com/ru/post/1715525/


All Articles