【问题标题】:Pytest: how to use --basetemp value in scriptPytest:如何在脚本中使用 --basetemp 值
【发布时间】:2022-10-16 06:41:16
【问题描述】:

我有需要创建一些文件的测试。 现在它看起来像我不使用临时目录。

class TestGraphProcessing:
    @pytest.mark.parametrize("graph, path_to_save", GRAPH_TO_FILE)
    def test_save_graph(self, graph, path_to_save):
        save_graph(graph, path_to_save)
        assert path_to_save.is_file()
        path_to_save.unlink()

    ...

我知道可以使用--basetemp 创建一个临时目录。但是如何将它提取到您的测试脚本中呢?

或者是否可以在测试期间以更优雅的方式创建和删除文件?

【问题讨论】:

    标签: python pytest


    【解决方案1】:

    您可以使用tmp_path 夹具。 docs 中有一个示例测试:

    # content of test_tmp_path.py
    CONTENT = "content"
    
    
    def test_create_file(tmp_path):
        d = tmp_path / "sub"
        d.mkdir()
        p = d / "hello.txt"
        p.write_text(CONTENT)
        assert p.read_text() == CONTENT
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多