|
发表于 2022-11-29 22:10:33
|
显示全部楼层
本楼为最佳答案
本帖最后由 阿奇_o 于 2022-11-29 22:12 编辑
你这是 自动化测试 的面试题?? 课程作业?? 我也没用过这个pytest,也不知道是否理解正确了题意(甚至觉得题目有点问题。。)
现学现卖,第一题大概这样实现吧:
- # conftest.py
- import pytest
- import pymysql
- @pytest.fixture(scope='function')
- def db_session():
- conn = pymysql.connect(
- host='localhost',
- user='root',
- password='123456',
- database='mydb',
- )
- yield conn
复制代码
- # test_pymysql.py
- import pymysql
- def test_init(db_session):
- assert db_session.user.decode() == 'root'
- assert db_session.db.decode() == 'mydb'
- # assert 0
- def test_conn(db_session):
- assert db_session.open == True
- def test_execute_sql(db_session):
- conn = db_session
- with conn.cursor() as cursor:
- cursor.execute("drop table if exists foo;")
- cursor.execute("create table if not exists foo(`id` int, `name` varchar(20), `age` int);")
- cursor.execute("insert into foo(`id`,`name`,`age`) values(1001, 'Alice', 18), (1002, 'Bill', 20);")
- cursor.execute("commit;")
- cursor.execute("select * from foo")
- result = cursor.fetchall()
- # for row in result: print(row)
- assert result == ((1001, 'Alice', 18), (1002, 'Bill', 20))
- # assert 0
- def test_close_conn(db_session):
- db_session.close()
- try:
- db_session.ping(reconnect=False)
- except pymysql.err.Error as e:
- # print(e, e.args)
- assert 'Already closed' in e.args[0]
- # assert 'Not closed ?' in e.args # deliberately fails
复制代码 |
|