Why doesn't my current directory show up in the path using pytest on Windows?

送分小仙女□ 提交于 2019-12-10 14:52:43

问题


I have the following folder structure;

myapp\
  myapp\
     __init__.py
  tests\
     test_ecprime.py

and my pwd is

C:\Users\wwerner\programming\myapp\

I have the following test setup:

import pytest
import sys
import pprint

def test_cool():
    pprint.pprint(sys.path)
    assert False

That produces the following paths:

['C:\\Users\\wwerner\\programming\\myapp\\tests',
 'C:\\Users\\wwerner\\programming\\envs\\myapp\\Scripts',
 'C:\\Windows\\system32\\python34.zip',
 'C:\\Python34\\DLLs',
 'C:\\Python34\\lib',
 'C:\\Python34',
 'C:\\Users\\wwerner\\programming\\envs\\myapp',
 'C:\\Users\\wwerner\\programming\\envs\\myapp\\lib\\site-packages']

And when I try to import myapp I get the following error:

ImportError: No module named 'ecprime'

So it looks like it's not adding the current directory to my path.

By changing my import line to look like this:

import sys
sys.path.insert(0, '.')
import myapp

I am then able to import myapp with no problems.

Why does my current directory not show up in the path when running pytest? Is my only workaround to insert . into the sys.path? (I'm using Python 3.4 if it matters)


回答1:


Ahah!

After comparing the layout of my cookiecutter repo, it turns out to be way more simple (and better) than that.

tests/
    __init__.py
    test_myapp.py

A simple addition of the __init__.py file to my test dir allows me to run py.test from my main directory.




回答2:


sys.path automatically has the script's directory in it, and not the current working directory.

I am guessing that your script in placed in tests directory. Based on this assumption, your code should look like this:

import sys
import os

ROOT_DIR = os.path.dirname(os.path.dirname(__file__))
sys.path.append(ROOT_DIR)

import myapp # Should work now



回答3:


Use the environment variable PYTHONPATH.

In Windows:

set PYTHONPATH=.
py.test

In Unix:

PYTHONPATH=. py.test


来源:https://stackoverflow.com/questions/21265061/why-doesnt-my-current-directory-show-up-in-the-path-using-pytest-on-windows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!