【问题标题】:Python Unit Test Start Directory Not ImportablePython 单元测试开始目录不可导入
【发布时间】:2020-07-14 19:59:41
【问题描述】:

我遇到了这个错误,并尝试了在这个网站上发布的一些修复,但都没有成功。我写了一个单元测试,由于Start Directory Not Importable 错误而无法调用它。我的文件结构是:

Root
    └── tests
        └── fixtures
            └── customFile.json
        ├── __init__.py
        └── functionTest.py
    └── Lambdas
        └── FunctionA
            ├── __init__.py
            └── FunctionToTest.py

我的单元测试看起来像这样:

import unittest
import json
import boto3

from Lambdas.FunctionA import FunctionToTest

s3 = boto3.client('s3', 'us-east-1')
file = s3.get_object(Bucket="BUCKET", Key="KEY")

mapper = s3.get_object(Key="KEY", Bucket="BUCKET")
mapperJSON = json.loads(mapper['Body'].read().decode('utf-8'))

path = r"./tests/fixtures/customFile.json"
with open(path) as file:
    endList = json.load(file)
    file.close()

class TestMatchModeler(unittest.TestCase):
    def test_run(self):
        test = FunctionToTest(file, mapperJSON)
        self.assertEqual(len(test), len(endList))


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

它正在测试的实际代码是:

def FunctionToTest(file, mapperjson):
    Fields = mapperjson['mappings']

    lines1 = file['Body'].read().decode('utf-8').split('\n')
    fieldnames = lines1[0].replace('"','').split(',')
    testls = [row for row in csv.DictReader(lines1[1:], fieldnames)]
    out = json.dumps(testls)
    jlist1 = json.loads(out)

    dicts = []
    Fieldsinv = {v: k for k, v in Fields.items()}
    for i in jlist1:
        d = {}
        for k, v in i.items():
            if k in Fieldsinv:
                d[Fieldsinv[k]] = v
        d['individual_id'] = str(uuid.uuid4())
        dicts.append(d)
    return dicts

基本上customFile.json 是我知道正确的字典列表,我想测试我的代码是否正确修改了 CSV 以具有相同数量的字典。这个问题被问了很多,答案总是通过init.py文件链接文件,但正如你所见,我已经这样做了,但它仍然不起作用。

我确定这可能会被标记为重复,但我不确定还有什么可以尝试的。

【问题讨论】:

    标签: python unit-testing testing


    【解决方案1】:

    您似乎缺少某些目录中的 __init__.py 文件:root、tests 和 lambdas。

    请看这里:python - unittest - ImportError: Start directory is not importable

    【讨论】:

    • 嗨@Artq99,我已将初始化文件添加到每个目录中,但不幸的是我仍然遇到同样的错误
    【解决方案2】:

    原来是运行这个命令

    python -m tests.functionTest
    

    成功了

    【讨论】:

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