python - 如何模拟 psycopg2 的紧密连接?
问题描述
我想使用 psycopg2 测试我的数据库类,但我遇到了问题 - 我不知道如何测试 close() 方法。我尝试了一些想法,这是下面的最后一个想法,但它不起作用。所以有人知道如何嘲笑吗?
数据库.py
import psycopg2
class DB:
def __init__(self, name: str) -> None:
self.name = name
self.conn = psycopg2.connect(dbname=self.name,
host="localhost",
port="5432",
user="postgres",
password="postgres")
def disconnect(self):
self.conn.close()
test_db.py
import unittest
from unittest import mock
import psycopg2
from db import DB
class TestDB(unittest.TestCase):
def setUp(self) -> None:
self.db = DB("testdb")
def tearDown(self) -> None:
self.db.disconnect()
@mock.patch("db.psycopg2.connect")
def test_DB_should_connect_to_db(self, mock_connect):
DB("testdb")
mock_connect.assert_called_with(dbname="testdb",
host="localhost",
port="5432",
user="postgres",
password="postgres")
@mock.patch("db.psycopg2.connect")
def test_db_should_disconnect_from_db(self, mock_connect):
mock_conn = mock_connect.return_value
mock_close = mock_conn.close
self.db.disconnect()
mock_close.assert_called_once()
if __name__ == '__main__':
unittest.main()
解决方案
推荐阅读
- python - Divide the dataframe1 column values with another dataframe column value
- haskell - Check if two Haskell functions are equal with regards to non-termination or errors
- html - Select Dropdown values based on input in textfield
- angular - mat-ink-bar location not update when container resizes
- java - 在方法 average() 中操作方法 sum()
- node.js - 通过函数结果设置对象键值
- java - 如何更新 ArrayList 中类实例的值
- php - MongoDB + PHP:过滤已解析的用户输入是否安全?
- python - 如何将请求的密码更改为名为`salt`和`pwdhash`的两个参数并将其保存到django中的数据库?
- shell - awk 根据匹配将列数据从一个文件输入到另一个文件