Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Forbid truthy values for lang when initializing Literal #1494

Merged
merged 3 commits into from
Dec 18, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion rdflib/term.py
Original file line number Diff line number Diff line change
Expand Up @@ -547,7 +547,7 @@ def __new__(cls, lexical_or_value, lang=None, datatype=None, normalize=None):
"per http://www.w3.org/TR/rdf-concepts/#section-Graph-Literal"
)

if lang and not _is_valid_langtag(lang):
if lang is not None and not _is_valid_langtag(lang):
raise ValueError("'%s' is not a valid language tag!" % lang)

if datatype:
Expand Down
37 changes: 32 additions & 5 deletions test/test_literal.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
from decimal import Decimal
from typing import Any, Optional, Type
import unittest
import datetime

import rdflib # needed for eval(repr(...)) below
from rdflib.term import Literal, URIRef, _XSD_DOUBLE, bind, _XSD_BOOLEAN
from rdflib.namespace import XSD

import pytest


class TestLiteral(unittest.TestCase):
def setUp(self):
Expand Down Expand Up @@ -42,17 +45,41 @@ def test_literal_from_bool(self):
self.assertEqual(l.datatype, rdflib.XSD["boolean"])


class TestNewPT:
# NOTE: TestNewPT is written for pytest so that pytest features like
# parametrize can be used.
# New tests should be added here instead of in TestNew.
@pytest.mark.parametrize(
"lang, exception_type",
[
({}, TypeError),
([], TypeError),
(1, TypeError),
(b"en", TypeError),
("999", ValueError),
("-", ValueError),
],
)
def test_cant_pass_invalid_lang(
self,
lang: Any,
exception_type: Type[Exception],
):
"""
Construction of Literal fails if the language tag is invalid.
"""
with pytest.raises(exception_type):
Literal("foo", lang=lang)


class TestNew(unittest.TestCase):
# NOTE: Please use TestNewPT for new tests instead of this which is written
# for unittest.
def testCantPassLangAndDatatype(self):
self.assertRaises(
TypeError, Literal, "foo", lang="en", datatype=URIRef("http://example.com/")
)

def testCantPassInvalidLang(self):
self.assertRaises(
ValueError, Literal, "foo", lang="999"
)

def testFromOtherLiteral(self):
l = Literal(1)
l2 = Literal(l)
Expand Down