将args作为unittest的一部分传递给测试pyspark脚本

时间:2018-11-15 12:22:54

标签: python unit-testing pyspark python-unittest args

我有一个python脚本,该脚本当前使用命令行参数'json文件的路径'并对数据进行一些清理。

我正在编写一些单元测试,试图将路径作为arg传递到json文件。当前没有提供arg时会出现错误,但通过时会出现错误:

AttributeError: 'module' object has no attribute 'data' which is data.json. 

我想拥有三个单独的单元测试,每个单元测试都有一个不同的json文件作为参数传递。

我的代码如下:

import unittest
import sys
import argparse

class TestTransform(unittest.TestCase):
    def test_transform(self,input_filename):
        target = __import__("cleaning.py")
        transform = target
        transform.ARGS(input_filename)
        self.assertTrue('Pass')

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

1 个答案:

答案 0 :(得分:0)

如果我正确理解了您的问题,这就是我通常在这种情况下所做的事情。我重写setUpClass方法,并为测试可以访问的此类属性进行所有输入:

class TestTransform():

    @classmethod
    def setUpClass(self, file_name):
        self.input_filename = file_name
        #Some other initialization code here

    def test_transform(self):
        target = __import__("cleaning.py")
        transform = target
        transform.ARGS(self.input_filename)
        self.assertTrue('Pass')

如果您随后要使用不同的输入值进行不同的测试,则可以通过将TestTransform类(当然还有unittest.TestCase)作为子类来创建其他类:

class Test1(TestTransform, unittest.TestCase):
    @classmethod
    def setUpClass(self):
        input_filename = 'MyFileName'
        #Here call the setUpClass from the TestTransform class
        TestTransform.setUpClass(input_filename)
相关问题