SQLHUB Telegram 2083
⚡️ Как тестировать код без настоящей базы данных

Когда вы пишете юнит-тесты, подключение к реальной БД — лишнее:

- это медленно,

- тесты становятся нестабильными,

- нужен живой сервер.

Решение — замокать вызов pandas.read_sql и вернуть подставные данные.

Пример функции:


def query_user_data(user_id):
query = f"SELECT id, name FROM users WHERE id = {user_id}"
return pd.read_sql(query, "postgresql://localhost/mydb")


Тест с моком:


from unittest.mock import patch
import pandas as pd

@patch("pandas.read_sql")
def test_database_query_mocked(mock_read_sql):
mock_read_sql.return_value = pd.DataFrame(
{"id": [123], "name": ["Alice"]}
)

result = query_user_data(user_id=123)
assert result["name"].iloc[0] == "Alice"


Теперь вместо запроса в реальную базу тест подставляет фейковые данные. Так можно проверить бизнес-логику функции быстро и надёжно.

@sqlhub
Please open Telegram to view this post
VIEW IN TELEGRAM
👍146😁1



tgoop.com/sqlhub/2083
Create:
Last Update:

⚡️ Как тестировать код без настоящей базы данных

Когда вы пишете юнит-тесты, подключение к реальной БД — лишнее:

- это медленно,

- тесты становятся нестабильными,

- нужен живой сервер.

Решение — замокать вызов pandas.read_sql и вернуть подставные данные.

Пример функции:


def query_user_data(user_id):
query = f"SELECT id, name FROM users WHERE id = {user_id}"
return pd.read_sql(query, "postgresql://localhost/mydb")


Тест с моком:


from unittest.mock import patch
import pandas as pd

@patch("pandas.read_sql")
def test_database_query_mocked(mock_read_sql):
mock_read_sql.return_value = pd.DataFrame(
{"id": [123], "name": ["Alice"]}
)

result = query_user_data(user_id=123)
assert result["name"].iloc[0] == "Alice"


Теперь вместо запроса в реальную базу тест подставляет фейковые данные. Так можно проверить бизнес-логику функции быстро и надёжно.

@sqlhub

BY Data Science. SQL hub




Share with your friend now:
tgoop.com/sqlhub/2083

View MORE
Open in Telegram


Telegram News

Date: |

The group’s featured image is of a Pepe frog yelling, often referred to as the “REEEEEEE” meme. Pepe the Frog was created back in 2005 by Matt Furie and has since become an internet symbol for meme culture and “degen” culture. Commenting about the court's concerns about the spread of false information related to the elections, Minister Fachin noted Brazil is "facing circumstances that could put Brazil's democracy at risk." During the meeting, the information technology secretary at the TSE, Julio Valente, put forward a list of requests the court believes will disinformation. To view your bio, click the Menu icon and select “View channel info.” Hui said the time period and nature of some offences “overlapped” and thus their prison terms could be served concurrently. The judge ordered Ng to be jailed for a total of six years and six months. Telegram desktop app: In the upper left corner, click the Menu icon (the one with three lines). Select “New Channel” from the drop-down menu.
from us


Telegram Data Science. SQL hub
FROM American