Correct approach to test drop table sqlite in unittest - python

I'm writing unit tests to test my environment.
I have created tests such as:
def test_database_file_present_and_readable(self):
self.assertTrue(os.access(path_db_file, os.R_OK))
def test_connect_to_db(self):
conn = sqlite3.connect(path_db_file)
conn.close()
def test_create_table(self):
conn = sqlite3.connect(path_db_file)
cur = conn.cursor()
cur.execute("CREATE TABLE test_table (id integer PRIMARY KEY, name text)")
conn.commit()
conn.close()
def test_insert_into_table(self):
conn = sqlite3.connect(path_db_file)
cur = conn.cursor()
cur.execute("insert into test_table (name) values (?)", ["Test value"])
conn.commit()
conn.close()
def test_update_table(self):
conn = sqlite3.connect(path_db_file)
cur = conn.cursor()
cur.execute("update test_table set id = 2 where id = ?", [1])
conn.commit()
conn.close()
def test_delete_from_table(self):
conn = sqlite3.connect(path_db_file)
cur = conn.cursor()
cur.execute("delete from test_table where id = ?", [2])
conn.commit()
conn.close()
def test_if_test_table_is_empty(self):
conn = sqlite3.connect(path_db_file)
cur = conn.cursor()
result = cur.execute("select exists(select 1 from test_table)").fetchall()
conn.commit()
conn.close()
self.assertTrue(result == 1)
def test_delete_table(self):
conn = sqlite3.connect(path_db_file)
cur = conn.cursor()
cur.execute("drop table test_table")
conn.commit()
conn.close()
And during program execution order of tests is unknown - how to set the order or how to clean up database after creating tests with table creation?

You can get pointers about test method execution order here: Python unittest.TestCase execution order
One suggestion - if you are going for such testing, it's better to mock external dependencies like sqlite & test only the code you've written.

Related

My Sqlite python code won't delete a record from a table [duplicate]

I made a module with the following contents:
import sqlite3 as sq
connection = sq.connect("test.db")
cursor = connection.cursor()
cursor.execute("DROP TABLE IF EXISTS test")
cursor.execute("CREATE TABLE test (st TEXT)")
cursor.execute("INSERT INTO test VALUES ('testing')")
cursor.execute("SELECT * FROM test")
print(cursor.fetchall())
cursor.close()
connection.close()
connection2 = sq.connect("test.db")
cursor2 = connection2.cursor()
cursor2.execute("SELECT * FROM test")
print(cursor2.fetchall())
But when I ran it, it printed the following:
[('testing',)]
[]
It should have printed:
[('testing',)]
[('testing',)]
What is wrong?
You did not commit your changes into the DB. When you discard the connection, the transaction will be rolled back. This works
import sqlite3 as sq
connection = sq.connect("test.db")
cursor = connection.cursor()
cursor.execute("DROP TABLE IF EXISTS test")
cursor.execute("CREATE TABLE test (st TEXT)")
cursor.execute("INSERT INTO test VALUES ('testing')")
connection.commit() # !!!
cursor.execute("SELECT * FROM test")
print(cursor.fetchall())
cursor.close()
connection.close() # rolls back changes without .commit()
connection2 = sq.connect("test.db")
cursor2 = connection2.cursor()
cursor2.execute("SELECT * FROM test")
print(cursor2.fetchall())

make temporary database with sqlite

I wanna make a temporary database but I don't know I going in the right way or not
I get the error no such table: list but I don't know why python raise that error
this is my code:
def connect():
conn = sqlite3.connect(":memory:")
cur = conn.cursor()
cur.execute(
"CREATE TABLE IF NOT EXISTS list (id INTEGER PRIMARY KEY , namee VARCHAR , number INTEGER ,"
" price INTEGER )"
)
conn.commit()
conn.close()
def insert(name, number, price):
conn = sqlite3.connect(":memory:")
cur = conn.cursor()
cur.execute(
"INSERT INTO list VALUES (NULL ,?,?,?,?,?)", (name, number, price)
)
conn.commit()
conn.close()
def view():
conn = sqlite3.connect(":memory:")
cur = conn.cursor()
cur.execute(
"SELECT * FROM list"
)
rows = cur.fetchall()
conn.close()
return rows
def delete(id):
conn = sqlite3.connect(":memory:")
cur = conn.cursor()
cur.execute("DELETE FROM list WHERE id=?", (id,))
conn.commit()
conn.close()
connect()
and this is my error:
Traceback (most recent call last):
File "D:\python\WindowsProject\app\user\memory.py", line 42, in <module>
print(insert('pizza',2,6))
File "D:\python\WindowsProject\app\user\memory.py", line 17, in insert
cur.execute(
sqlite3.OperationalError: no such table: list
sqlite3.connect(":memory:") creates an in-memory database that only exists as long as the connection is in use.
The problem is that you're closing the database connection in each function. As soon as you close it, the in-memory database vanishes. INSERT fails because the table no longer exists.
You'll need to preserve (or pass) the conn and cur objects so that you can use them between functions.

how to use one database in several python file

I working on a project and I want to use one database in two python file
but, when I run every project they created database for self
if you know please tell me how I can use that
import sqlite3
def connect():
conn = sqlite3.connect("waiters.db")
cur = conn.cursor()
cur.execute(
"CREATE TABLE IF NOT EXISTS salary (id INTEGER PRIMARY KEY , name text, age INTEGER , price INTEGER )"
)
conn.commit()
conn.close()
def insert(name, age, price):
conn = sqlite3.connect("waiters.db")
cur = conn.cursor()
cur.execute(
"INSERT INTO salary VALUES (NULL ,?,?,?)", (name ,age ,price)
)
conn.commit()
conn.close()
def view():
conn = sqlite3.connect("waiters.db")
cur = conn.cursor()
cur.execute(
"SELECT * FROM salary"
)
rows = cur.fetchall()
conn.close()
return rows
def search(name="", age="", price=""):
conn = sqlite3.connect("waiters.db")
cur = conn.cursor()
cur.execute(
"SELECT * FROM salary WHERE name = ? OR age = ? OR price = ?", (name, age, price)
)
rows = cur.fetchall()
conn.close()
return rows
def delete(id):
conn = sqlite3.connect("waiters.db")
cur = conn.cursor()
cur.execute("DELETE FROM salary WHERE id=?", (id,))
conn.commit()
conn.close()
def update(id, name, age, price):
conn = sqlite3.connect("waiters.db")
cur = conn.cursor()
cur.execute(
"UPDATE salary SET name = ?, age = ?, price = ? WHERE id = ?", (name, age, price, id)
)
conn.commit()
conn.close()
def update_pay_money(name, price):
conn = sqlite3.connect("waiters.db")
cur = conn.cursor()
cur.execute(
"UPDATE salary SET price = ? WHERE name = ?", (price, name)
)
conn.commit()
conn.close()
connect()
enter image description here
Giving exact path like /path/to/waiters.db while connecting to your database should solve your problem?
This line should be changed while connecting to database.
conn = sqlite3.connect("/path/to/waiters.db")
as Other mentioned for using a sqllite3 db in multiple files you can use their absolute or relative path, for example if you have 'DBs' & 'section-1' & 'section-2' directories and your python file are in section directories you can access the database file in each section by using somthing like this '"../DBs/waiters.db"' and so on for others... but whatf of you try make multiple tables in a database file in tgat way you don need to have multiple databases and its the standard way,
hope it's help

Basic Database made with SQLITE3

I created a basic database in python with sqlite3 which takes in 3 values and stores them. Now where the problem lies is that when I created a function that is supposed to output the values, no syntax errors were displayed on terminal and none of my values were printed. Im guessing this is a minor error but I am not able to spot it.
The code is given below:
import sqlite3
def create_table():
conn = sqlite3.connect("lite.db")
cur = conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS store (item TEXT, quantity
INTEGER, price FLOAT)")
conn.commit()
conn.close()
def insert(item, quantity, price):
conn = sqlite3.connect("lite.db")
cur = conn.cursor()
cur.execute("INSERT INTO store VALUES ('?, ?, ?')", (item, quantity,
price))
conn.commit()
conn.close()
insert("Mug", 8, 6)
def view():
conn = sqlite3.connect("lite.db")
cur = conn.cursor()
cur.execute("SELECT * FROM store")
rows = cur.fetchall()
conn.close()
return rows
print(view())
Again no error messages were displayed but my values are not displayed.
I have tried it. it seems the single quotes are not needed in the insert. See modified below:
import sqlite3
def create_table():
conn = sqlite3.connect("lite.db")
cur = conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS store (item TEXT, quantity INTEGER, price FLOAT)")
conn.commit()
conn.close()
def insert(item, quantity, price):
conn = sqlite3.connect("lite.db")
cur = conn.cursor()
cur.execute("INSERT INTO store VALUES (?,?,?)", (item, quantity, price))
conn.commit()
conn.close()
def view():
conn = sqlite3.connect("lite.db")
cur = conn.cursor()
cur.execute("SELECT * FROM store")
rows = cur.fetchall()
conn.close()
return rows
create_table()
insert("Mug", 1, 5)
print(view())

SQLite not saving data between uses

I made a module with the following contents:
import sqlite3 as sq
connection = sq.connect("test.db")
cursor = connection.cursor()
cursor.execute("DROP TABLE IF EXISTS test")
cursor.execute("CREATE TABLE test (st TEXT)")
cursor.execute("INSERT INTO test VALUES ('testing')")
cursor.execute("SELECT * FROM test")
print(cursor.fetchall())
cursor.close()
connection.close()
connection2 = sq.connect("test.db")
cursor2 = connection2.cursor()
cursor2.execute("SELECT * FROM test")
print(cursor2.fetchall())
But when I ran it, it printed the following:
[('testing',)]
[]
It should have printed:
[('testing',)]
[('testing',)]
What is wrong?
You did not commit your changes into the DB. When you discard the connection, the transaction will be rolled back. This works
import sqlite3 as sq
connection = sq.connect("test.db")
cursor = connection.cursor()
cursor.execute("DROP TABLE IF EXISTS test")
cursor.execute("CREATE TABLE test (st TEXT)")
cursor.execute("INSERT INTO test VALUES ('testing')")
connection.commit() # !!!
cursor.execute("SELECT * FROM test")
print(cursor.fetchall())
cursor.close()
connection.close() # rolls back changes without .commit()
connection2 = sq.connect("test.db")
cursor2 = connection2.cursor()
cursor2.execute("SELECT * FROM test")
print(cursor2.fetchall())

Categories