Skip to content

Commit

Permalink
test: update test_steam_workshop.py for 100% coverage
Browse files Browse the repository at this point in the history
  • Loading branch information
Nicconike committed Jun 29, 2024
1 parent 82bf032 commit 72c964f
Showing 1 changed file with 81 additions and 23 deletions.
104 changes: 81 additions & 23 deletions tests/test_steam_workshop.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Test Steam Workshop Script"""
# Disable pylint warnings for false positives
# pylint: disable=duplicate-code
from unittest.mock import MagicMock, patch
# pylint: disable=duplicate-code, unused-argument
from unittest.mock import MagicMock, patch, Mock
import pytest
import requests
from api.steam_workshop import (
Expand Down Expand Up @@ -31,9 +31,9 @@ def test_get_server_info_success(requests_mock):
)
result = get_server_info("dummy_api_key")
if result is None:
raise AssertionError("Expected result to be not None")
if result is None or "servertime" not in result:
raise AssertionError("Expected 'servertime' to be in result")
pytest.fail("Expected result to be not None")
if "servertime" not in result:
pytest.fail("Expected 'servertime' to be in result")


def test_get_server_info_http_error(requests_mock):
Expand All @@ -44,7 +44,7 @@ def test_get_server_info_http_error(requests_mock):
)
result = get_server_info("dummy_api_key")
if result is not None:
raise AssertionError("Expected result to be None")
pytest.fail("Expected result to be None")


def test_get_server_info_request_exception(requests_mock):
Expand All @@ -55,7 +55,7 @@ def test_get_server_info_request_exception(requests_mock):
)
result = get_server_info("dummy_api_key")
if result is not None:
raise AssertionError("Expected result to be None")
pytest.fail("Expected result to be None")


def test_is_server_online_success(requests_mock):
Expand All @@ -66,7 +66,7 @@ def test_is_server_online_success(requests_mock):
)
result = is_server_online("dummy_api_key")
if not result:
raise AssertionError("Expected result to be True")
pytest.fail("Expected result to be True")


def test_is_server_online_http_error(requests_mock):
Expand All @@ -77,7 +77,7 @@ def test_is_server_online_http_error(requests_mock):
)
result = is_server_online("dummy_api_key")
if result:
raise AssertionError("Expected result to be False")
pytest.fail("Expected result to be False")


def test_is_server_online_request_exception(requests_mock):
Expand All @@ -88,7 +88,7 @@ def test_is_server_online_request_exception(requests_mock):
)
result = is_server_online("dummy_api_key")
if result:
raise AssertionError("Expected result to be False")
pytest.fail("Expected result to be False")


def test_extract_links():
Expand All @@ -104,7 +104,7 @@ def test_extract_links():
expected_result = [
"https://steamcommunity.com/id/nicconike/myworkshopfiles/"]
if result != expected_result:
raise AssertionError(f"Result should be {expected_result}")
pytest.fail(f"Result should be {expected_result}")


def test_has_next_page():
Expand All @@ -113,7 +113,7 @@ def test_has_next_page():
mock_soup.find.return_value = MagicMock(find=MagicMock(return_value=True))
result = has_next_page(mock_soup)
if not result:
raise AssertionError("Expected result to be True")
pytest.fail("Expected result to be True")


def test_handle_request_exception():
Expand All @@ -123,23 +123,81 @@ def test_handle_request_exception():
mock_logger.error.assert_called_with(
"Connection error occurred. Please check your network connection")

handle_request_exception(requests.exceptions.Timeout())
mock_logger.error.assert_called_with(
"Request timed out. Please try again later")

handle_request_exception(requests.exceptions.TooManyRedirects())
mock_logger.error.assert_called_with(
"Too many redirects. Check the URL and try again")

response_mock = Mock()
response_mock.status_code = 404
response_mock.reason = "Not Found"
handle_request_exception(
requests.exceptions.HTTPError(response=response_mock))
mock_logger.error.assert_called_with(
"HTTP error occurred: %s - %s", "404", "Not Found")

handle_request_exception(Exception("Some error"))
mock_logger.error.assert_called_with(
"An error occurred: %s", "Some error")

def test_fetch_workshop_item_links_success(requests_mock):

@patch('api.steam_workshop.is_server_online', return_value=True)
@patch('api.steam_workshop.extract_links', return_value=["https://steamcommunity.com/sharedfiles/filedetails/?id=2984474065"])
@patch('api.steam_workshop.has_next_page', return_value=False)
def test_fetch_workshop_item_links_success(mock_has_next_page, mock_extract_links, mock_is_server_online, requests_mock):
"""Test successful fetching of workshop item links"""
requests_mock.get(
'https://steamcommunity.com/id/dummy_custom_id/myworkshopfiles/?p=1',
text='<div class="workshopItem"><a class="ugc"'
'href="https://steamcommunity.com/sharedfiles/filedetails/?id=2984474065"></a></div>'
)
requests_mock.get(
'https://api.steampowered.com/ISteamWebAPIUtil/GetServerInfo/v1/',
json={"servertime": 1234567890}
)
result = fetch_workshop_item_links("dummy_custom_id", "dummy_api_key")
expected_result = [
"https://steamcommunity.com/sharedfiles/filedetails/?id=2984474065"]
if result != expected_result:
raise AssertionError(f"Result should be {expected_result}")
pytest.fail(f"Result should be {expected_result}")


@patch('api.steam_workshop.is_server_online', return_value=False)
def test_fetch_workshop_item_links_server_offline(mock_is_server_online):
"""Test fetching workshop item links when server is offline"""
with pytest.raises(ConnectionError,
match="Steam Community is currently offline. Please try again later"):
fetch_workshop_item_links("dummy_custom_id", "dummy_api_key")


@patch('api.steam_workshop.is_server_online', return_value=True)
@patch('api.steam_workshop.extract_links', return_value=[])
@patch('api.steam_workshop.has_next_page', return_value=False)
def test_fetch_workshop_item_links_no_items(mock_has_next_page, mock_extract_links,
mock_is_server_online, requests_mock):
"""Test fetching workshop item links with no items found"""
requests_mock.get(
'https://steamcommunity.com/id/dummy_custom_id/myworkshopfiles/?p=1',
text='<div class="noItems"></div>'
)
with pytest.raises(ValueError, match="No items were found in your Steam Workshop"):
fetch_workshop_item_links("dummy_custom_id", "dummy_api_key")


@patch('api.steam_workshop.is_server_online', return_value=True)
@patch('api.steam_workshop.extract_links', side_effect=AttributeError("Parsing error"))
def test_fetch_workshop_item_links_parsing_error(mock_extract_links,
mock_is_server_online, requests_mock):
"""Test fetching workshop item links with parsing error"""
requests_mock.get(
'https://steamcommunity.com/id/dummy_custom_id/myworkshopfiles/?p=1',
text='<div class="workshopItem"></div>'
)
with patch('api.steam_workshop.logger') as mock_logger:
with pytest.raises(ValueError, match="No items were found in your Steam Workshop"):
fetch_workshop_item_links("dummy_custom_id", "dummy_api_key")
mock_logger.error.assert_called_with(
"Parsing error: %s. The structure of the page might have changed", "Parsing error"
)


def test_fetch_individual_workshop_stats_success(requests_mock):
Expand All @@ -152,7 +210,7 @@ def test_fetch_individual_workshop_stats_success(requests_mock):
expected_result = {"unique_visitors": 1000,
"current_subscribers": 0, "current_favorites": 0}
if result != expected_result:
raise AssertionError(f"Result should be {expected_result}")
pytest.fail(f"Result should be {expected_result}")


def test_fetch_all_workshop_stats_success(requests_mock):
Expand All @@ -163,10 +221,10 @@ def test_fetch_all_workshop_stats_success(requests_mock):
)
result = fetch_all_workshop_stats(["http://example.com"])
if result["total_unique_visitors"] != 1000:
raise AssertionError("Total unique visitors should be 1000")
pytest.fail("Total unique visitors should be 1000")
if result["total_current_subscribers"] != 0:
raise AssertionError("Total current subscribers should be 0")
pytest.fail("Total current subscribers should be 0")
if result["total_current_favorites"] != 0:
raise AssertionError("Total current favorites should be 0")
pytest.fail("Total current favorites should be 0")
if len(result["individual_stats"]) != 1:
raise AssertionError("Length of individual stats should be 1")
pytest.fail("Length of individual stats should be 1")

0 comments on commit 72c964f

Please sign in to comment.