Python - 组织代码和测试套件

时间:2013-06-22 09:27:12

标签: python

我是python的新手,来自php背景,无法找出组织代码的最佳方法。

目前我正在通过项目euler练习来学习python。我希望有一个目录可以解决问题,还有一个目录可以反映这个问题。

理想情况:

Problem
    App
        main.py
    Tests
        maintTest.py

使用php这非常简单,因为我可以只需要正确的文件,或修改include_path

如何在python中实现?显然这是一个非常简单的例子 - 因此关于如何更大规模地处理这一问题的一些建议也将非常感激。

2 个答案:

答案 0 :(得分:0)

这取决于您要使用的测试运行器。

<强> pytest

我最近学会了pytest

它有一个关于how to organize the code的部分。

如果您无法将主要密码导入代码,那么您可以使用下面的技巧。

<强>单元测试

当我使用unittest时,我这样做:

使用导入主

Problem
    App
        main.py
    Tests
        test_main.py

test_main.py

import sys
import os
import unittest
sys.path.append(os.path.join(os.path.dirname(__file__), 'App'))
import main

# do the tests

if __name__ == '__main__':
    unittest.run()

或使用导入App.main

Problem
    App
        __init__.py
        main.py
    Tests
        test.py
        test_main.py

test.py

import sys
import os
import unittest
sys.path.append(os.path.dirname(__file__))

test_main.py

from test import *
import App.main

# do the tests

if __name__ == '__main__':
    unittest.run()

答案 1 :(得分:0)

我一直很喜欢nosetests,所以这是我的解决方案:

  

问题

App

    __init__.py
    main.py

Tests

    __init__.py
    tests.py

然后,打开命令提示符,将CD打开到/path/to/Problem并输入:

  

nosetests测试

它会自动识别并运行测试。但是,请阅读:

  

匹配的任何python源文件,目录或包   testMatch正则表达式(默认情况下:(?:^ | [b _.-])[Tt] \ test)将是   收集作为测试(或测试集合的来源)。   [...]

     

在测试目录或包中,将检查与testMatch匹配的任何python源文件以获取测试用例。在测试模块中,名称与具有任何名称的testMatch和TestCase子类匹配的函数和类将作为测试加载和执行。

这基本上意味着您的测试(包括文件和函数/方法/类)必须以“test”或“Test”字开头。

有关Nosetests用法的更多信息,请访问:Basic Usage