2017-05-23 52 views
1

我想用pytest编写一个测试,当一个函数在不同的运行中有不同的结果时,它会失败。一个简单的例子是hash("abc")使用pytest测试不同运行/进程的一致性

在终端:

$> python -c 'print(hash("abc"))' 
7757446167780988571 
$> python -c 'print(hash("abc"))' 
-1754122997235049390 

然而在一次运行,我们当然有:

>>> hash("abc") 
-2233283646379253139 
>>> hash("abc") 
-2233283646379253139 

我如何写一个测试(使用pytest),它测试使用不同进程/运行的函数结果的一致性,以至于hash("abc")会失败?

背景是我正在实现一个数据库访问函数,该函数比较了酸洗/碾磨字典的二进制字符串。但是,对于同一个字典,这些字符串会因运行而异。 我想测试的一致性,因为该功能不应该添加到数据库,如果字典已经在它..

+0

是的,它的工作原理,谢谢!但是,对于实际的问题,这并不是真的可行。因为我打电话的功能需要相当多的灯具。我会检查我是否找到一种方法使其工作。 – Thomasillo

回答

0

基于多夫Benyomin Sohacheskis答案,我结束了以下解决方案,以测试功能与测试夹具和一致性所有的更复杂的问题..

我会在这里发布因为它也可能对其他人有帮助。 我假设fixture持有argskwargs要测试的功能。

import tempfile 
import dill 
import functools 
import subprocess 

def test_consistency_of_f(fixture): 

    args, kwargs = fixture 

    f = functools.partial(function_to_be_tested, *args, **kwargs) 

    with tempfile.TemporaryDirectory() as td: 
     fn = os.path.join(td, 'test.dill') 
     with open(fn, 'wb') as fi: 
      dill.dump(f, fi) 
     cmd = """import dill 
with open('{}', 'rb') as fi: 
    f=dill.load(fi) 
print(f()) 
""".format(fn) 
     cmd = ['python', '-c', cmd] 
     s1 = subprocess.check_output(cmd) 
     s2 = subprocess.check_output(cmd) 
     if not s1 == s2: 
      print(1, s1) 
      print(2, s2) 
     assert s1 == s2 
0

它的黑客攻击的解决方案,但你可以使用流程来实现你的目标。

import subprocess 

def test_hash(): 
    # Create the command 
    cmd = ['python', '-c', 'print(hash("abc"), end="")'] 

    # Run a sub-process 
    other_hash = subprocess.check_output(cmd) 

    assert hash('abc') != int(other_hash) 
相关问题