1

I wanted to get advice on the best way to setup a simple app with pytest.

I can run pytest fine on a single file but I wanted to bootstrap a Python app using:

mypkg/
    __init__.py
    app.py
tests/
    __init__.py
    test_app.py

But when I run pytest I get an error:

NameError: name 'func' is not defined

mypkg/__init__.py file

# content of __init__.py
# Empty init file

mypkg/app.py file

# content of app.py
class mypkg:
    def func(x):
        return x + 1

tests/__init__.py file

# content of __init__.py
# Empty init file

tests/test_app.py file

# content of test_app.py
import pytest
import mypkg

def test_answer():
    assert func(4) == 5

I'm using Python 3.5.

Do I need a setup.py and if I try calling mypkg.func(4) instead I get an AttributeError: modulemypkghas no attribute 'func'.

Any help is much appreciated.

2 Answers 2

2

This question has nothing to do with pytest, or with testing at all. It is a fundamental rule in Python that if you want to access a name you need to import it; you haven't imported func, so it gives a name error.

However, for some reason you have defined func as part of a class. You cannot import a method separately from its class; but, there is no reason for that to be a method in a class at all. Just define it as a standalone function, and import that.

Note, even standing on its own, func is inside app, not directly inside mypkg. So you need to import it where it actually is.

from mypkg.app import func
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Daniel :) I understand now that the period between mypkg and app = the directory mypkg/app. Also, I've remove the class and have the method stands alone now.
0

You declared func inside mypkg class that resides inside mypkg/app.py module, thus you need to rewrite your tests as follows

# content of test_app.py
import pytest
import mypkg

def test_answer():
    obj = mypkg.app.mypkg()
    assert obj.func(4) == 5

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.