2

I have a following solution structure:

main
main/src/myApi.py
main/unittests/myApiTests.py

in myApiTests.py I try to import the class Database from myApi.py but i get the following error every time I try:

Traceback (most recent call last): File "S:...\main\UnitTests\myApiTests.py", line 3, in from myApi import Database ModuleNotFoundError: No module named 'myApi'

import sys
sys.path.append("../src")
from myApi import Database
import unittest


class BotApiTests(unittest.TestCase):
    def test_GetUserBalance_WhenUserDoesNotExist_ThenReturn0(self):
        testDatabase = Database('testDb.db')
        userName = "testUserName"

        result = testDatabase.GetUserBalance(userName)
        self.assertEqual(result, 0)

unittest.main()

I've also tried

sys.path.append("..src")

or

sys.path.append("..")

or

from myApi import Database

but nothing works :-(

Edit: I have an empty __init__.py in every folder

Edit2: Full Code:

main/src/myApi.py:

import re
import string
import urllib.request
import sqlite3
import praw

class Database:   
    def __init__(self, name='cryptotipbot.db'):
        print("in __init__ -> ", (name))
        self.connection = sqlite3.connect(name, check_same_thread=False)
        self.database = self.connection.cursor()
        self.CreateDatabase()
        self.addressIndex = len(self.database.execute("SELECT * FROM usedAdresses").fetchall())

    def CreateDatabase(self):
        print("in CreateDatabase")
        self.database.execute("CREATE TABLE IF NOT EXISTS Users (redditUsername TEXT PRIMARY KEY, balance INTEGER)")
        self.connection.commit()
        self.database.execute("CREATE TABLE IF NOT EXISTS CommentsRepliedTo (commentId TEXT PRIMARY KEY)")
        self.connection.commit()
        self.database.execute("CREATE TABLE IF NOT EXISTS UsedAdresses (adressIndex INTEGER PRIMARY KEY, adress TEXT)")
        self.connection.commit()
        self.database.execute("CREATE TABLE IF NOT EXISTS DepositRequests (messageId TEXT PRIMARY KEY, adress TEXT, amount INTEGER)")
        self.connection.commit()

    def CreateUser(self, redditUsername):
        user = self.database.execute("SELECT * FROM Users WHERE redditUsername = ?", (redditUsername,)).fetchone()
        if not user:
            self.database.execute("INSERT INTO Users (redditUsername, balance) VALUES (?, ?)", (redditUsername, 0))
            self.connection.commit()

    def GetUserBalance(self, redditUsername):
        entry = self.database.execute("SELECT * FROM Users WHERE redditUsername = ?",(redditUsername,)).fetchone()
        if entry:
            balance = entry[1]
            return balance
        else:
            self.CreateUser(redditUsername)
            return self.GetUserBalance(redditUsername)

main/UnitTests/myApiTests.py

import unittest
from ..src import myApi

class BotApiTests(unittest.TestCase):
    def test_GetUserBalance_WhenUserDoesNotExist_ThenReturn0(self):
        testDatabase = Database('testDb.db')
        userName = "testUserName"

        result = testDatabase.GetUserBalance(userName)
        self.assertEqual(result, 0)


unittest.main()
xeraphim
  • 4,375
  • 9
  • 54
  • 102
  • 1
    The modules are not at the same level. Also `Database` is not a module, I guess it is a class. – Stop harming Monica Nov 07 '17 at 21:44
  • sorry yes, it's a class... what do you mean they are not on the same level? – xeraphim Nov 07 '17 at 21:45
  • I read "the same level" as "the same directory" but now I think I see what you mean. Actually I do not think the "level" is relevant. – Stop harming Monica Nov 07 '17 at 21:50
  • I tried to replicate your setup and it works for me. Maybe you misspelled something or are running the test script from a different directory. – Stop harming Monica Nov 07 '17 at 21:55
  • hm... did you also use `import sys sys.path.append("../src") from myApi import Database`? how did you run the tests? I'm running them via `python.exe S:\..\main\UnitTests\myApiTests.py` – xeraphim Nov 07 '17 at 22:05
  • You need to run it from the `UnitTests` directory. – Stop harming Monica Nov 07 '17 at 22:07
  • yes I'm doing that... :-S – xeraphim Nov 07 '17 at 22:08
  • Possible duplicate of [How to do relative imports in Python?](https://stackoverflow.com/questions/72852/how-to-do-relative-imports-in-python) – noslenkwah Nov 07 '17 at 22:17
  • Try just `python myApiTests.py` (why do you provide the full path if you are in the same directory?), make sure it is the correct python (I guess you are using python3 but you did not tell), check what `"../src"` resolves to, get rid of the `__init__.py` files if only to reduce noise (you do not want those directories to be packages do you?), add details about what you are doing **in the question** to avoid misunderstandings (copy the prompt, the command and the output as it appears in the console)... – Stop harming Monica Nov 07 '17 at 22:25
  • Also `sys.path.append("..\\src")` or use `os.path.join`. Are you sure slashes are ok in `sys.path` in windows? I guess they are but I cannot tell for sure. – Stop harming Monica Nov 07 '17 at 22:31
  • I'm not sure, if slashes are ok... this is the first time I do something with python – xeraphim Nov 08 '17 at 06:30
  • I've added the whole source code to the original post – xeraphim Nov 08 '17 at 06:31
  • @xeraphim How came `sys.path.append("../src")` is not in the full code but it is in the not-so-full code? – Stop harming Monica Nov 08 '17 at 12:20
  • @Goyo its because I try different things out :-) I've tried both – xeraphim Nov 08 '17 at 12:32

0 Answers0