Skip to content

Commit

Permalink
test: refactor tests into separate scripts to reduce complexity and i…
Browse files Browse the repository at this point in the history
…mprove readability
  • Loading branch information
MountainGod2 committed Oct 3, 2024
1 parent f1c0c6a commit 7c735a3
Show file tree
Hide file tree
Showing 24 changed files with 1,546 additions and 1,438 deletions.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@
line-length = 100
lint.fixable = ["ALL"]
lint.ignore = ["COM812", "D203", "D213", "INP001", "ISC001"]
lint.per-file-ignores."tests/*" = ["S101", "SLF001"]
lint.per-file-ignores."tests/*" = ["S101", "SLF001", "ANN401", "FBT001", "PLR0913", "SIM117", "PLR2004", "D100"]
lint.pydocstyle.convention = "google"
lint.select = ["ALL"]
lint.unfixable = []
Expand Down
6 changes: 2 additions & 4 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
"""Fixtures for pytests."""

import asyncio
import logging
from typing import Any
Expand Down Expand Up @@ -88,7 +86,7 @@ def setup_logging() -> None:


@pytest.fixture
def http_client_mock(mocker: MockerFixture) -> Any: # noqa: ANN401
def http_client_mock(mocker: MockerFixture) -> Any:
"""Fixture for mocking the httpx.AsyncClient.get method."""
return mocker.patch("httpx.AsyncClient.get")

Expand All @@ -100,7 +98,7 @@ def chaturbate_client() -> ChaturbateClient:


@pytest.fixture
def mock_influxdb_handler(mocker: Any) -> Any: # noqa: ANN401
def mock_influxdb_handler(mocker: Any) -> Any:
"""Fixture for the InfluxDB handler."""
return mocker.Mock()

Expand Down
2 changes: 0 additions & 2 deletions tests/constants.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
"""Constants for pytests."""

USERNAME = "testuser"
TOKEN = "testtoken" # noqa: S105
TEST_URL = f"https://eventsapi.chaturbate.com/events/{USERNAME}/{TOKEN}/"
Expand Down
59 changes: 59 additions & 0 deletions tests/test_backoff_handlers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import logging
from typing import Any

import pytest
from httpx import (
HTTPStatusError,
Request,
Response,
)

from chaturbate_poller.utils import ChaturbateUtils


class TestBackoffHandlers:
"""Tests for the backoff handlers."""

@pytest.mark.parametrize(
("wait", "tries", "expected_log"),
[
(1.0, 1, "Backing off 1 seconds after 1 tries"),
(2.0, 3, "Backing off 2 seconds after 3 tries"),
],
)
def test_backoff_handler(self, caplog: Any, wait: float, tries: int, expected_log: str) -> None:
"""Test the backoff handler with different parameters."""
caplog.set_level(logging.INFO)
ChaturbateUtils().backoff_handler({
"wait": wait,
"tries": tries,
"target": lambda x: x,
"args": (),
"kwargs": {},
"elapsed": 0,
})
assert expected_log in caplog.text

def test_giveup_handler(self, caplog: Any) -> None:
"""Test the giveup handler."""
caplog.set_level(logging.ERROR)
ChaturbateUtils().giveup_handler({ # type: ignore[typeddict-item, typeddict-unknown-key]
"tries": 6,
"exception": HTTPStatusError(
message="Server Error",
request=Request("GET", "https://error.url.com"),
response=Response(500, json={"status": "Unknown error"}),
),
})
assert "Giving up after 6 tries due to server error code 500: Unknown error" in caplog.text

def test_giveup_handler_no_exception(self, caplog: Any) -> None:
"""Test the giveup handler with no exception."""
caplog.set_level(logging.ERROR)
ChaturbateUtils().giveup_handler({ # type: ignore[typeddict-item]
"tries": 6,
})
assert (
"Giving up after 6 tries due to server error code None: No response available"
in caplog.text
)
63 changes: 63 additions & 0 deletions tests/test_chaturbate_client_initialization.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import asyncio

import pytest

from chaturbate_poller.chaturbate_client import ChaturbateClient
from chaturbate_poller.constants import API_TIMEOUT, TESTBED_BASE_URL

from .constants import TOKEN, USERNAME


class TestChaturbateClientInitialization:
"""Tests for the initialization of ChaturbateClient."""

@pytest.mark.asyncio
async def test_initialization(self) -> None:
"""Test successful initialization of ChaturbateClient with default settings."""
async with ChaturbateClient(USERNAME, TOKEN) as client:
assert client.username == USERNAME
assert client.token == TOKEN

@pytest.mark.asyncio
async def test_initialization_with_timeout(self) -> None:
"""Test ChaturbateClient initialization with custom timeout."""
timeout = API_TIMEOUT
async with ChaturbateClient(USERNAME, TOKEN, timeout=timeout) as client:
assert client.timeout == timeout

@pytest.mark.asyncio
async def test_initialization_with_testbed(self) -> None:
"""Test ChaturbateClient initialization with testbed base URL."""
async with ChaturbateClient(USERNAME, TOKEN, testbed=True) as client:
assert client.base_url == TESTBED_BASE_URL

@pytest.mark.parametrize(("username", "token"), [("", TOKEN), (USERNAME, ""), ("", "")])
@pytest.mark.asyncio
async def test_initialization_failure(self, username: str, token: str) -> None:
"""Test ChaturbateClient initialization failure with missing username or token."""
with pytest.raises(ValueError, match="Chaturbate username and token are required."):
async with ChaturbateClient(username, token):
await asyncio.sleep(0)

@pytest.mark.asyncio
async def test_initialization_with_invalid_timeout(self) -> None:
"""Test ChaturbateClient initialization with invalid timeout."""
invalid_timeout = "invalid_timeout"
with pytest.raises(TypeError):
async with ChaturbateClient(USERNAME, TOKEN, timeout=invalid_timeout): # type: ignore[arg-type]
pass

@pytest.mark.asyncio
async def test_initialization_with_negative_timeout(self) -> None:
"""Test ChaturbateClient initialization with negative timeout."""
negative_timeout = -1
with pytest.raises(ValueError, match="Timeout must be a positive integer."):
async with ChaturbateClient(USERNAME, TOKEN, timeout=negative_timeout):
pass

@pytest.mark.asyncio
async def test_initialization_with_missing_env_variables(self) -> None:
"""Test ChaturbateClient initialization with missing environment variables."""
with pytest.raises(ValueError, match="Chaturbate username and token are required."):
async with ChaturbateClient("", ""):
pass
Loading

0 comments on commit 7c735a3

Please sign in to comment.