【问题标题】:Conflict with loading up mock data for unit testing between PyCharm and unittests在 PyCharm 和单元测试之间加载模拟数据以进行单元测试的冲突
【发布时间】:2020-05-29 06:38:52
【问题描述】:

我有一个 Python 项目结构如下。

. ├── 数据 ├── 源 │   ├── 模块1 │   └── 模块2 └── 测试 ├── 基地 ├── 模块1 └── 模块2

data 目录是我放置用于单元测试的模拟数据(例如 CSV 文件)的位置。如果我在 PyCharm 中,在单元测试中,我可以使用如下的相对路径并使用 IDE 成功运行单元测试(使用unittests)。

pd.read_csv('../../data/mock.csv')

但是,在 PyCharm 之外,我可以尝试运行以下命令来运行单元测试。

python -m unittest tests/module1/*.py

我会收到一条错误消息,指出该文件不存在。如果我如下更改路径,则从 PyCharm 外部运行单元测试有效,但在 PyCharm 中运行测试失败。

pd.read_csv('./data/mock.csv')

当我检查单元测试配置时,我注意到working directory 设置为/Users/myusername/myproject/tests/module1。如果我将工作目录更改为/Users/myusername/myproject,则会收到以下错误:AssertionError: Path must be within the project

我什至尝试将data 目录移动到tests > module1,但同样的冲突仍然存在;现在 pd.read_csv('./data/mock.csv') 适用于 PyCharm,但在终端上失败了。

关于如何解决这个冲突的任何想法?

【问题讨论】:

    标签: python unit-testing pycharm


    【解决方案1】:

    我通过抽象出获取模拟数据的路径来解决这个问题。

    def normalize_path(resource, proj_root='root_folder'):
        path = os.getcwd() # current working directory
        tokens = path.split('/') # tokens of directory path
        index = tokens.index(proj_root) # look for where project root ends
        tokens = tokens[1:index + 1] # reconstruct the path up to the project root
        p = '/'.join(tokens)
        p = f'/{p}/{resource}' # append the resource to the project root
    
        return p
    

    在我的代码中,现在我执行以下操作。

    pd.read_csv(normalize_path('data/mock.csv'))
    

    我可以毫无问题地从终端或 PyCharm 执行测试。

    【讨论】:

      猜你喜欢
      • 2016-12-09
      • 1970-01-01
      • 2020-04-06
      • 2018-09-04
      • 2013-11-12
      • 2018-11-21
      • 2018-10-19
      • 2013-07-24
      • 1970-01-01
      相关资源
      最近更新 更多