Python数据库测试实战指南

  • Python
    sqlalchemy库
    pymysql库(本文以mysql为例,所以选择该mysql驱动库)
    unittest
    以下代码示例仅验证以下几个目标:
  • 表名
  • 字段名
  • 主键
import unittest

from sqlalchemy import create_engine
from sqlalchemy.engine import reflection


class TestMySQL(unittest.TestCase):
    def setUp(self):
        # 创建连接
        self.engine = create_engine("mysql+pymysql://root:[email protected]:3306/mysql")

        # 创建inspector对象
        self.insp = reflection.Inspector.from_engine(self.engine)

    def test_table_name(self):
        # 判断user表是否在mysql这个实例库中
        self.assertIn("user", self.insp.get_table_names())

    def test_column(self):
        # user表中是否有User字段
        User = None
        columns = self.insp.get_columns("user")
        for col in columns:
            if "User" == col["name"]:
                User = col["name"]

        self.assertIsNotNone(User)

    def test_keyprimary(self):
        # 验证user表中User字段是否为主键
        k = self.insp.get_pk_constraint("user")
        self.assertIn("User", k["constrained_columns"])


if __name__ == "__main__":

    unittest.main()

你可能感兴趣的:(Python数据库测试实战指南)