【问题标题】:Key - Error when running in Travis CI| Pytest关键 - 在 Travis CI 中运行时出错| pytest
【发布时间】:2019-08-10 16:20:14
【问题描述】:

在 Travis CI 上运行 Pytest 时,我收到 Key -Error。请在下面找到我的程序:

import sys
import os
sys.path.append(os.path.dirname(__file__)+"/../")
from src.read_files import VEHICLE_DATA
from src.main import create_parser

def getvehicles(climate):
    '''
       :param climate: type of climate
       :return: Based on climate, return available vehicles
    '''

    bike = VEHICLE_DATA['bike']
    tuktuk = VEHICLE_DATA['tuktuk']
    car = VEHICLE_DATA['car']

    if climate == "Sunny":
        vehicle = [[bike, tuktuk, car], -0.1]
    elif climate == "Rainy":
        vehicle = [[car, tuktuk], 0.2]
    else:
        vehicle = [[car, bike], 0.0]
    return vehicle

对应的pytest如下:

import sys
import os
sys.path.append(os.path.dirname(__file__)+"/../")
from src import traffic_problem_1 as tp
import pytest

@pytest.mark.parametrize('climate, speed',          \
                        [                           \
                            ('Sunny', -0.1),        \
                            ('Windy', 0.0),         \
                            ('Rainy', 0.2)
                        ])
def test_when_climate_sunny_return_all_vechicles(climate, speed):
    crater_speed = tp.getvehicles(climate)
    assert crater_speed[1] == speed

以上测试在我的本地机器上成功运行。但不是我 Travis CI,请找到 Travis CI 日志的链接:

https://travis-ci.org/pythonprogsnscripts/geekttrustproblems/builds/570241873

如果退伍军人能提出一些想法,那就太好了

【问题讨论】:

  • 问题出在src.read_files,检查一下。同时使用 mock 让这个测试通过,unittest 不应该依赖于设置错误。
  • 但在我的本地机器上也是如此,您能否通过一些线索了解可能是什么问题?

标签: python pytest travis-ci pytest-cov


【解决方案1】:

os.listdir 不保证确定的文件顺序;它会因操作系统和文件系统组合而异。来自the docs

os.listdir(path='.')

返回一个列表,其中包含由 path 给出的目录中的条目名称。该列表按任意顺序 [...]

在您的情况下,这意味着JSON_FILES[1] 在某些系统上将是vehicle_data.json,而在其他系统上将是orbit_data.json,从而导致测试失败。解决方案是自己强制执行命令,例如通过排序:

JSON_FILES = sorted(os.listdir('inputdata'))

【讨论】:

  • 很高兴能帮上忙!
猜你喜欢
  • 1970-01-01
  • 2017-04-09
  • 1970-01-01
  • 2016-05-03
  • 2018-03-14
  • 1970-01-01
  • 2016-05-09
  • 1970-01-01
  • 2017-11-12
相关资源
最近更新 更多