pytest tmpdir_factory 测试 glob 搜索

pytest tmpdir_factory test glob search

我正在尝试编写一个测试来验证当我遍历目录时是否找到了正确的文件,但我不明白为什么在执行代码时使用 tmpdir_factory,glob 返回为空在真正的目录上按预期工作。所有模块导入都是正确的,它正在调用该函数。

待测代码:

def get_files(sdir, extension):
    return glob.glob1(sdir, "*" + extension + "*")

pytest代码:

flist = [
    "12707054321.HOM0LRP2.COUNTS.JOB46147.pg96.afp.2017011",
    "22707054321.HOM0LRP2.COUNTS.JOB46147.pg96.afp.2017012",
    "32707054321.HOM0LRP2.COUNTS.JOB46147.pg96.afp.2017013",
    "42707054321.HOM0LRP2.COUNTS.JOB46147.pg96.afp.2017014",
    "52707054321.HOM0LRP2.COUNTS.JOB46147.pg96.afp.2017015",
    "12707054321.HOM0LRP2.COUNTS.JOB46147.pg96.afp.2017011.pdpr",
    "22707054321.HOM0LRP2.COUNTS.JOB46147.pg96.afp.2017012.pdpr",
    "32707054321.HOM0LRP2.COUNTS.JOB46147.pg96.afp.2017013.pdpr",
    "42707054321.HOM0LRP2.COUNTS.JOB46147.pg96.afp.2017014.pdpr",
    "52707054321.HOM0LRP2.COUNTS.JOB46147.pg96.afp.2017015.pdpr"
]


def test_get_files_afp(tmpdir_factory):
    rlist = [
        "12707054321.HOM0LRP2.COUNTS.JOB46147.pg96.afp.2017011",
        "22707054321.HOM0LRP2.COUNTS.JOB46147.pg96.afp.2017012",
        "32707054321.HOM0LRP2.COUNTS.JOB46147.pg96.afp.2017013",
        "42707054321.HOM0LRP2.COUNTS.JOB46147.pg96.afp.2017014",
        "52707054321.HOM0LRP2.COUNTS.JOB46147.pg96.afp.2017015"
    ]
    test_dir = tmpdir_factory.mktemp('testdata')
    for f in flist:
        test_dir.join(f)

    lst = get_files(sdir=str(test_dir), extension=".afp")
    assert lst == rlist

失败:

assert lst == rlist
E       AssertionError: assert [] == ['12707054321.HOM0LRP2.COUNT....JOB46147.pg96.afp.2017015']
E         Right contains more items, first extra item: 
'12707054321.HOM0LRP2.COUNTS.JOB46147.pg96.afp.2017011'
E         Full diff:
E         - []
E         + ['12707054321.HOM0LRP2.COUNTS.JOB46147.pg96.afp.2017011',
E         +  '22707054321.HOM0LRP2.COUNTS.JOB46147.pg96.afp.2017012',
E         +  '32707054321.HOM0LRP2.COUNTS.JOB46147.pg96.afp.2017013',
E         +  '42707054321.HOM0LRP2.COUNTS.JOB46147.pg96.afp.2017014',...

在 tmpdir/tmpdir_factory 中,只有在您写入文件后才会真正创建文件。

变化:

for f in flist:
    test_dir.join(f)

for f in flist:
    a = test_dir.join(f)
    a.write('')

创建文件并按预期工作