简体   繁体   English

多个线程中的Python单元测试

[英]Python unit-testing in multiple threads

I would like to unit-test the functionality of a few classes that mainly do file in- and output. 我想对一些主要用于文件输入和输出的类的功能进行单元测试。 Furthermore I would like to do that on multiple cores (--jobs=4). 此外,我想在多个内核上执行此操作(--jobs = 4)。

The problem is, that the files that are created by the classes often have the same name and they get mixed up in multiple threads. 问题是,由类创建的文件通常具有相同的名称,并且在多个线程中混杂在一起。 What I do currently is that I run each unit-test in a separate directory like so: 我目前要做的是,在这样的单独目录中运行每个单元测试:

def test(self):
  if os.path.exists("UniqueDir"):
    os.system("rm -rf UniqueDir")
  os.mkdir("UniqueDir")
  os.chdir("UniqueDir")
  #Do the actual testing
  os.chdir("..")
  os.rmdir("UniqueDir")

The downsides are very obvious: 缺点非常明显:

  1. Each test must receive a unique directory name 每个测试必须收到一个唯一的目录名称
  2. Each test has this overhead of source which really is not pleasant to look at at all 每个测试都有这种源代码的开销,这看起来一点都不令人愉快

What approach could I use to 1. separate my tests from one another but 2. do it in a more elegant way? 我可以使用哪种方法1.将测试彼此分开,但是2.以一种更优雅的方式进行?

Any help, suggestion etc. is appreciated! 任何帮助,建议等,不胜感激!

Cherio Woltan 凯里奥·沃尔坦(Cherio Woltan)

I would suggest to use the unittest module and build the classes like this: 我建议使用unittest模块并构建如下的类:

import unittest
from tempfile import mkdtemp

class Test(unittest.TestCase):

    def setUp(self):
        self.tempdir = mkdtemp()
        os.chdir(self.tempdir)

    def tearDown(self):
        os.rmdir(self.tempdir)

    def testName(self):
        #Do the actual testing
        pass

if __name__ == "__main__":
    unittest.main()

Additionally you could add multiprocessing to create 4 threads. 另外,您可以添加多处理以创建4个线程。

Edit: removed the os.mkdir because mkdtemp creates a temp directory so it's bogus. 编辑:删除了os.mkdir,因为mkdtemp创建了一个临时目录,所以它是虚假的。 Thx Sebastian. 塞巴斯蒂安(Thx Sebastian)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM