파이썬 / db test / mysql test / test 방법 / db 쉽게
database query 관련 python unittest
import unittest
from datetime import datetime
import pymysql
class TestInsertPurchaseData(unittest.TestCase):
def shortDescription(self):
# 이것을 하지 않으면 첫줄만 print 된다. [ref. 1]
return self._testMethodDoc
@classmethod
def setUpClass(cls):
cls.conn = pymysql.connect(
host="localhost",
user="root",
password="namhun",
cursorclass=pymysql.cursors.DictCursor,
)
cls.db = 'testdb'
cls._setUpCreateDB(cls.db)
cursor = cls.conn.cursor()
cursor.execute(f"use {cls.db}")
# query from .sql file
with open('schema.sql', encoding='utf8') as f:
commands = f.read().split(';')
for command in commands:
if command.strip() != "":
cursor.execute(command)
@classmethod
def tearDownClass(cls):
# drop test database
try:
cls.cursor.execute(f"DROP DATABASE {cls.db}")
cls.conn.commit()
cls.cursor.close()
except pymysql.Error as err:
print(f"Database {cls.db} does not exists. Dropping db failed")
cls.conn.close()
@classmethod
def _setUpCreateDB(cls, db):
cursor = cls.conn.cursor()
try:
cursor.execute(f"DROP DATABASE {db}")
cursor.close()
print("DB dropped")
except pymysql.Error as err:
print(f"{db}{err}")
cursor.close()
# create database
cls.cursor = cls.conn.cursor()
try:
cls.cursor.execute(f"CREATE DATABASE {db} DEFAULT CHARACTER SET 'utf8'")
except pymysql.Error as err:
print(f"Failed creating database: {err}")
exit(1)
def test_insert_record(self):
"""
Test whether the inserted row count is correct
"""
pass
if __name__ == "__main__":
# 이것은 python -m unittest 로 하면 호출이 되지 않는다. `python -m unittest test.py`
unittest(verbosity=2)
CREATE TABLE `product_price` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`purchase_date` date NOT NULL COMMENT '',
`total_amount` int(11) NOT NULL COMMENT '',
`total_price` bigint(20) NOT NULL COMMENT '',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
CREATE TABLE `price2` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`sales_date` date NOT NULL COMMENT '',
`price2` int(11) NOT NULL COMMENT '',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4;
INSERT INTO mapping (id,`sales_date`,price2) VALUES
(1,'2022-01-01',3558),
(2,'2022-01-02',40000);
unittest verbose option
unittest(verbosity=2)
를 하면, test case 를 실행할때
첫줄을 print 해준다.[ref. 1]
다음 부분은 python -m unittest test.py
를 실행하면
실행되지 않는다. __name__
값이 '__main__'
이
아니기 때문이다.
python -m unittest -v test.py
를 하면
verbosity=2
와 같은 결과가 나온다.
if __name__ == "__main__":
unittest(verbosity=2)
댓글 없음:
댓글 쓰기