Skip to content

Commit

Permalink
🦺 Validate priority (#14)
Browse files Browse the repository at this point in the history
### TL;DR

This PR adds priority field validation for SiteMapUrl in the sitemapr module, including corresponding exception handling and tests for invalid values.

### What changed?

- Added `SiteMaprException` and `InvalidSiteMapPriority` in `sitemapr.exceptions`.
- Added priority validation in `SiteMapUrl` model (with corresponding validator).
- Added unit tests for the newly added validation logic in `tests/test_core.py`.
- .gitignore now tracks the .python-version file.

### How to test?

- Run `pytest` to ensure all test cases, especially the new ones for priority validation, pass successfully.

### Why make this change?

- Adding priority validation ensures that the priority values are within the acceptable range (0.0 to 1.0), thus maintaining data integrity.
  • Loading branch information
mingi3314 authored Jul 10, 2024
1 parent dc29cda commit 9364289
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 2 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
.python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
Expand Down
19 changes: 18 additions & 1 deletion sitemapr/models.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from collections.abc import Callable
from decimal import Decimal
from typing import Literal, TypeVar

from pydantic import BaseModel
from pydantic import BaseModel, ValidationError, validator

T = TypeVar("T")

Expand Down Expand Up @@ -30,3 +31,19 @@ class SiteMapUrl(BaseModel):
lastmod: str | None = None
changefreq: ChangeFreq | None = None # Google ignores this
priority: str | None = None # Google ignores this

@validator("priority")
def validate_priority(cls, v: str | None) -> str | None:
if v is None:
return v
try:
priority = Decimal(v)
except Exception as e:
raise ValidationError(
"Priority must be a valid decimal string between 0.0 and 1.0"
) from e

if 0 <= priority <= 1:
return f"{priority:.1f}"

raise ValidationError("Priority must be between 0.0 and 1.0")
26 changes: 26 additions & 0 deletions tests/test_core.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import pathlib

import pytest
from pydantic import ValidationError

from sitemapr import Page, Param, SiteMapr, SiteMapUrl


Expand Down Expand Up @@ -168,6 +171,29 @@ def test_iter_url_works():
assert actuals == expected


def test_iter_url_raises_error_when_priority_is_invalid():
"""iter_url should raise an error when priority is invalid."""
# given
invalid_priority = "1.1"

base_url = "https://example.com"
pages = [
Page(
path="",
query_params=[
Param(name="page", values=["home", "about", "contact"]),
Param(name="sort", values=["asc", "desc"]),
],
priority=invalid_priority,
),
]
sitemapr = SiteMapr(base_url=base_url, pages=pages)

# when, then
with pytest.raises(ValidationError):
list(sitemapr.iter_urls())


def test_save_works(tmp_path: pathlib.Path):
"""save should save sitemap.xml when there is only one page."""
# given
Expand Down

0 comments on commit 9364289

Please sign in to comment.