How to write Python unit tests for scripts in my bin directory

The Python module unittestseems to suggest a directory structure for a project that has a project root directory with source code and tests in that directory.

I would like, however, to write Python scripts in my directory ~/binand test it in another directory (say, ~/dev/tests). Is there a way to run unit tests using the command line interface without setting my environment variable PYTHONPATHand creating files __init__.pyand whatnot?

Here is a simple example demonstrating what I want:

~/bin/candy:

#!/usr/bin/env python

def candy():
    return "candy"

if __name__ == '__main__':
    print candy()

~/dev/tests/test_candy.py:

#!/usr/bin/env python

import unittest
import candy

class CandyTestCase(unittest.TestCase):

    def testCandy(self):
        candyOutput = candy.candy()

        assert candyOutput == "candy"

I notice that everything can be done conveniently if:

  • Two files are named with extensions py ( candy.pyand test_candy.py)
  • Two files are in the same directory.
  • : $ python -m unittest test_candy

python unittest, , :

  • py ( ~/candy).
  • , test_candy py .
  • , candy test_candy.py ( ).

python -m unittest, ?

+4

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


All Articles