Python Forum
Problems with importing classes in different folder
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Problems with importing classes in different folder
#1
Hey guys

I try to reference the class Database in my unit test.
This is the first time I program with python so I hope I explain everything correctly :-)

I have a following solution structure:

Quote:> 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:

Quote:>Traceback (most recent call last):
File "S:\...\main\UnitTests\myApiTests.py", line 3, in <module>
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 :-(

I have an empty __init__.py in every folder

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()
Reply
#2
You need to provide __init__.py at top level, and
empty __init__.py in src and sub-folders.
See: https://docs.python.org/3/tutorial/modul...l#packages
The top level __init__.py lets python know where dependencies are located.
Reply
#3
Hmm I already tried to have an empty __init__.py in every folder but that didn't work...

Does the __init__.py at top level have to have some content?
Reply
#4
Read the docs.  See link in previous post.
The one at the top describes all of the dependencies.
It is not empty.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Compare folder A and subfolder B and display files that are in folder A but not in su Melcu54 3 466 Jan-05-2024, 05:16 PM
Last Post: Pedroski55
  Compare filename with folder name and copy matching files into a particular folder shantanu97 2 4,391 Dec-18-2021, 09:32 PM
Last Post: Larz60+
  Move file from one folder to another folder with timestamp added end of file shantanu97 0 2,438 Mar-22-2021, 10:59 AM
Last Post: shantanu97
  Python Cut/Copy paste file from folder to another folder rdDrp 4 4,945 Aug-19-2020, 12:40 PM
Last Post: rdDrp
  Problems with inheritance with classes internetguy 3 2,546 Jul-04-2019, 11:59 AM
Last Post: metulburr
  Encoding problems on multiple files in one folder NikolajKorsgaard 5 3,944 Jun-11-2019, 03:39 AM
Last Post: micseydel
  Including classes from folder issue graham23s 1 1,940 Apr-03-2019, 07:33 AM
Last Post: Gribouillis
  Problems parsing /proc folder anddontyoucomebacknomore 2 2,514 Mar-06-2019, 09:16 PM
Last Post: DeaD_EyE
  Delete directories in folder is not working after folder is updated asheru93 2 2,601 Feb-13-2019, 12:37 PM
Last Post: asheru93
  Importing classes? frequency 11 4,708 Dec-31-2018, 07:21 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020