2013-06-22 77 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