【问题标题】:Alternative to hardcoding Python interpreter exec during unittest在单元测试期间硬编码 Python 解释器 exec 的替代方法
【发布时间】:2018-12-05 20:40:36
【问题描述】:

假设一个 unittest 测试,其中通过 Python 脚本(使用 argparse)生成一个多行输出文件,并将该文件与预期结果的相等性进行比较。

def test_actual_vs_expected_output(self):
    actual_inp = '/path_to/actu_inp.txt'
    expect_otp = '/path_to/expe_otp.txt'
    actual_otp = '/path_to/actu_otp.txt'
    myScript = '/path_to/myScript.py'
    cmd_list = ['python2', myScript,
                '-i', actual_inp,
                '-o', actual_otp]
    try:
        subprocess.check_output(' '.join(cmd_list), shell=True)
    except subprocess.CalledProcessError as e:
        print e.output
    if os.path.isfile(actual_otp):
        expect_str = open(expect_otp).read()
        actual_str = open(actual_otp).read()
    self.assertMultiLineEqual(expect_str, actual_str)

如何避免对python2 的调用进行硬编码(即在上述示例的cmd_list 中)?毕竟,Python2 解释器在不同系统上的调用方式可能不同。

【问题讨论】:

    标签: python python-2.7 unit-testing command-line


    【解决方案1】:

    要在子进程中调用 Python,您可以使用当前正在运行的 Python 解释器。这个解释器的完整路径由全局变量sys.executable 给出。

    所以,你可以写:

    import sys
    
    cmd_list = [sys.executable, myScript,
                '-i', actual_inp,
                '-o', actual_otp]
    

    注释:subprocess.check_output 函数接受参数列表,因此您可以按原样传递 cmd_list 参数(您不需要加入):

    subprocess.check_output(cmd_list, shell=True)
    

    另一条评论:python 脚本可能会在 STDERR 中写入错误消息。您可以考虑使用check_output 的替代方法来获取错误消息或使用stderr=subprocess.STDOUT

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-23
      • 2012-05-04
      • 1970-01-01
      • 2016-04-10
      相关资源
      最近更新 更多