2

so im making a basic calculator. For the sake of simplicity lets assume the whole code is

import math

class Calculator:

  def __init__(self):
    self.answer = 0.00


  def addition(self,num1,num2):
    self.answer = num1 + num2
    return self.answer

The file above is calculator.py

My Pytest file is called test_calculator.py and has the following code:

import pytest
from calculator import Calculator


def test_answer_init(calculator):
  calculator = Calculator()
  assert calculator.answer == 0.00

However, when i run the test i get the following error:

___ ERROR collecting test/test_calculator.py _________________________
ImportError while importing test module '/Users/Jacob/Desktop/Python/test/test_calculator.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
/usr/local/Cellar/python@3.9/3.9.9/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py:127: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
test/test_calculator.py:2: in <module>
    from calculator import Calculator
E   ModuleNotFoundError: No module named 'calculator'

Could someone pleaw tell me the proper way to import my class

1 Answers1

1

You might be missing an empty __init__.py in your folder, which is needed to designate it as a Python package, and therefore be able to import modules from it.

See https://stackoverflow.com/a/4116384 for more details.

And you should change test_calculator.py to:

import pytest
from .calculator import Calculator


def test_answer_init():
  calculator = Calculator()
  assert calculator.answer == 0.00
Michael Mintz
  • 9,007
  • 6
  • 31
  • 48