2013-06-22 73 views
1

我对python非常陌生,来自php背景,无法找出组织代码的最佳方式。Python - 组织代码和测试套件

目前我正在通过项目euler练习来学习python。我想为我的解决方案提供一个目录和一个用于测试的目录。

那么理想:

Problem 
    App 
     main.py 
    Tests 
     maintTest.py 

使用PHP,这是很容易的,因为我可以只require_once正确的文件,或修改include_path

这怎么能在python中实现?显然,这是一个非常简单的例子 - 因此,如何更大规模地接触这个问题,一些建议也将非常感激。

+0

查看相关问题http://stackoverflow.com/questions/1849311/how-should-i-organize-python-source-code – user1929959

回答

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() 
+0

在这个例子中,__init__.py有用吗? –

+0

'__init __。py'是一个使App成为一个包的空文件。这导致'import app'导入'App/__ init __。py',并且你可以用'import App.main'导入'App/main'。 – User

+0

因此python可以看到任何__init__.py文件并将该位置添加到路径中? –

0

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

Problem

App 

    __init__.py 
    main.py 

Tests 

    __init__.py 
    tests.py 

然后,打开命令提示符,光盘/path/to/Problem和类型:

nosetests Tests

它会自动识别并运行测试。但是,这样说的:

Any python source file, directory or package that matches the testMatch regular expression (by default: (?:^|[b_.-])[Tt]est) will be collected as a test (or source for collection of tests). [...]

Within a test directory or package, any python source file matching testMatch will be examined for test cases. Within a test module, functions and classes whose names match testMatch and TestCase subclasses with any name will be loaded and executed as tests.

这基本上意味着你的测试(包括您的文件和功能/方法/班)必须开始与“测试”或“测试”字样。

更多Nosetests使用说明:Basic Usage