From c5927347c44af5c24c5a0caf074b8deaa73015e0 Mon Sep 17 00:00:00 2001 From: Poonam Baxi Date: Thu, 7 Jan 2021 11:49:40 -0800 Subject: [PATCH 1/4] Test Request: Placeholder explanations #7 https://github.com/microsoft/localizationkit/issues/7 --- localizationkit/localization_types.py | 7 ++ localizationkit/tests/__init__.py | 1 + .../tests/placeholder_token_explanation.py | 95 +++++++++++++++++++ tests/test_placeholder_token_explanation.py | 88 +++++++++++++++++ 4 files changed, 191 insertions(+) create mode 100644 localizationkit/tests/placeholder_token_explanation.py create mode 100644 tests/test_placeholder_token_explanation.py diff --git a/localizationkit/localization_types.py b/localizationkit/localization_types.py index f839114..58fa749 100644 --- a/localizationkit/localization_types.py +++ b/localizationkit/localization_types.py @@ -36,6 +36,13 @@ def tokens(self) -> List[str]: """ return LocalizedString._TOKEN_PATTERN.findall(self.value) + def comment_tokens(self) -> List[str]: + """Find and return the tokens in the comment string. + + :returns: The list of tokens in the comment string + """ + return LocalizedString._TOKEN_PATTERN.findall(self.comment) + def __str__(self) -> str: """Generate and return the string representation of the object. diff --git a/localizationkit/tests/__init__.py b/localizationkit/tests/__init__.py index 141f1cc..3449564 100644 --- a/localizationkit/tests/__init__.py +++ b/localizationkit/tests/__init__.py @@ -11,3 +11,4 @@ import localizationkit.tests.swift_interpolation import localizationkit.tests.token_matching import localizationkit.tests.token_position_identifiers +import localizationkit.tests.placeholder_token_explanation diff --git a/localizationkit/tests/placeholder_token_explanation.py b/localizationkit/tests/placeholder_token_explanation.py new file mode 100644 index 0000000..aeb6cee --- /dev/null +++ b/localizationkit/tests/placeholder_token_explanation.py @@ -0,0 +1,95 @@ +"""Placeholder token explanation.""" + +from typing import Any, Dict, List, Set + +from localizationkit.tests.test_case import LocalizationTestCase + + +class PlaceholderTokenExplanation(LocalizationTestCase): + """Check the placeholder tokens in strings have explanation in comments.""" + + @classmethod + def name(cls) -> str: + return "placeholder_token_explanation" + + @classmethod + def default_settings(cls) -> Dict[str, Any]: + return {"always": False} + + def run_test(self) -> List[str]: + + violations = [] + + for string in self.collection.localized_strings: + tokens = string.tokens() + comment_tokens = string.comment_tokens() + + if not tokens or len(tokens) == 0: + if comment_tokens or len(comment_tokens) > 0: + violations.append(f"Comment string has extra token explanations: {string}") + continue + continue + + if not comment_tokens or len(comment_tokens) == 0: + violations.append(f"Comment string is missing all token explanation: {string}") + continue + + if len(comment_tokens) < len(tokens): + violations.append(f"Comment string is missing explanantion for some tokens: {string}") + continue + + if len(comment_tokens) > len(tokens): + violations.append(f"""Comment string has explanation for extra tokens + that are not a part of the string : {string}""") + continue + + # Validate token format in both string and comment string if it has single token + if len(tokens) < 2: + if "%@" not in tokens[0]: + violations.append(f"String missing correctly formatted token: {string}") + continue + if "%@" not in comment_tokens[0]: + violations.append(f"String comment missing correctly formatted token: {string}") + continue + continue + + # Validate position of both tokens and comment tokens to make sure all placeholder tokens + # in string have corresponding explanation in the comment string + positional_tokens: Set[int] = set() + comment_positional_tokens: Set[int] = set() + + for token in tokens: + if "$" not in token: + violations.append(f"String missing positional tokens: {string}") + continue + + position = int((token.split("$")[0]).replace("%", "")) + + if position in positional_tokens: + violations.append(f"Duplicate token position: {string}") + continue + + positional_tokens.add(position) + + for token in comment_tokens: + if "$" not in token: + violations.append(f"Comment string missing positional tokens: {string}") + continue + + position = int((token.split("$")[0]).replace("%", "")) + + if position in comment_positional_tokens: + violations.append(f"Duplicate comment token position: {string}") + continue + + comment_positional_tokens.add(position) + + for i in range(1, len(tokens) + 1): + if i not in positional_tokens: + violations.append(f"Token position index skipped: {string}") + + for i in range(1, len(comment_tokens) + 1): + if i not in comment_positional_tokens: + violations.append(f"Comment Token position index skipped: {string}") + + return violations diff --git a/tests/test_placeholder_token_explanation.py b/tests/test_placeholder_token_explanation.py new file mode 100644 index 0000000..23b20bf --- /dev/null +++ b/tests/test_placeholder_token_explanation.py @@ -0,0 +1,88 @@ +"""Placeholder token explanation tests.""" + +# pylint: disable=line-too-long + +import os +import sys +import unittest + +sys.path.insert(0, os.path.abspath(os.path.join(os.path.abspath(__file__), "..", ".."))) +import localizationkit + + +class PlaceholderTokenExplanationTests(unittest.TestCase): + """Placeholder token explanation tests.""" + + def setUp(self): + current_file_path = os.path.abspath(__file__) + current_folder_path = os.path.dirname(current_file_path) + self.config_path = os.path.abspath(os.path.join(current_folder_path, "config.toml")) + self.configuration = localizationkit.Configuration.from_file(self.config_path) + + def test_placeholder_token_explanation(self): + """Test that all placeholder token explanations exists in comments""" + test_cases = [ + ( + True, + localizationkit.LocalizedString( + "Key", "This is a string with no tokens", "Some comment", "en" + ), + ), + ( + True, + localizationkit.LocalizedString( + "Key", "This is a string with one token: %@", "Some comment %@ token explanation", "en" + ), + ), + ( + True, + localizationkit.LocalizedString( + "Key", "This is a string with two tokens: %1$@ %2$@", "Some comment %1$@ token explanantion %2$@ token explanantion", "en" + ), + ), + ( + False, + localizationkit.LocalizedString( + "Key", + "This is a string with two tokens: %1$@ %2$@", + "Some comment missing all token explanation", + "en", + ), + ), + ( + False, + localizationkit.LocalizedString( + "Key", "This is a string with two tokens: %1$@ %2$@", "Some comment %@ token explanation missing some token explanantion", "en" + ), + ), + ( + False, + localizationkit.LocalizedString( + "Key", "This is a string", "Some comment %@ extra token explanation", "en" + ), + ), + ( + False, + localizationkit.LocalizedString( + "Key", "This is a string with two incorrect positioned tokens %1$@ %3$@", "Some comment %1$@ token explanantion %2$@ token explanantion", "en" + ), + ), + ( + False, + localizationkit.LocalizedString( + "Key", "This is a string with two tokens: %1$@ %2$@", "Some comment with incorrect poistioned token explanantion %1$@ token explanation %3$@ token explanation", "en" + ), + ), + ] + + for (expected_result, string) in test_cases: + collection = localizationkit.LocalizedCollection([string]) + test = localizationkit.tests.placeholder_token_explanation.PlaceholderTokenExplanation( + self.configuration, + collection + ) + result = test.execute() + if expected_result: + self.assertTrue(result.succeeded()) + else: + self.assertFalse(result.succeeded()) From 63a1887d743f4ffe767d46dec586ee9492975ab5 Mon Sep 17 00:00:00 2001 From: Poonam Baxi Date: Thu, 14 Jan 2021 13:28:38 -0800 Subject: [PATCH 2/4] Address review comments --- README.md | 8 ++ localizationkit/tests/__init__.py | 4 +- .../tests/placeholder_token_explanation.py | 79 +++---------------- tests/test_placeholder_token_explanation.py | 19 +---- 4 files changed, 22 insertions(+), 88 deletions(-) diff --git a/README.md b/README.md index 6cc08c9..6c01b19 100644 --- a/README.md +++ b/README.md @@ -232,6 +232,14 @@ Check that each token has a position specifier with it. e.g. `%s` is not allowed +## Placeholder token explanation + +Identifier: `placeholder_token_explanation` +Opt-In: `true` + +Checks that if a placeholder is used in a string, the comment explicitly explain what it is replaced with. +Precondition: Each placeholder in the string and its explanation in comment is expected to follow `token_position_identifiers` rule. + # Contributing This project welcomes contributions and suggestions. Most contributions require you to agree to a diff --git a/localizationkit/tests/__init__.py b/localizationkit/tests/__init__.py index 3449564..48616f0 100644 --- a/localizationkit/tests/__init__.py +++ b/localizationkit/tests/__init__.py @@ -8,7 +8,7 @@ import localizationkit.tests.invalid_tokens import localizationkit.tests.key_length import localizationkit.tests.objectivec_alternative_tokens +import localizationkit.tests.placeholder_token_explanation import localizationkit.tests.swift_interpolation import localizationkit.tests.token_matching -import localizationkit.tests.token_position_identifiers -import localizationkit.tests.placeholder_token_explanation +import localizationkit.tests.token_position_identifiers \ No newline at end of file diff --git a/localizationkit/tests/placeholder_token_explanation.py b/localizationkit/tests/placeholder_token_explanation.py index aeb6cee..18cb137 100644 --- a/localizationkit/tests/placeholder_token_explanation.py +++ b/localizationkit/tests/placeholder_token_explanation.py @@ -1,6 +1,6 @@ """Placeholder token explanation.""" -from typing import Any, Dict, List, Set +from typing import Any, Dict, List from localizationkit.tests.test_case import LocalizationTestCase @@ -14,82 +14,23 @@ def name(cls) -> str: @classmethod def default_settings(cls) -> Dict[str, Any]: - return {"always": False} + return {} def run_test(self) -> List[str]: violations = [] for string in self.collection.localized_strings: - tokens = string.tokens() - comment_tokens = string.comment_tokens() + tokens = set(string.tokens()) + comment_tokens = set(string.comment_tokens()) - if not tokens or len(tokens) == 0: - if comment_tokens or len(comment_tokens) > 0: - violations.append(f"Comment string has extra token explanations: {string}") - continue - continue + extra_in_tokens = tokens - comment_tokens + extra_in_comments = comment_tokens - tokens - if not comment_tokens or len(comment_tokens) == 0: - violations.append(f"Comment string is missing all token explanation: {string}") - continue + if len(extra_in_tokens) != 0: + violations.append(f"Tokens are not described in the comment ({extra_in_tokens}): {string}") - if len(comment_tokens) < len(tokens): - violations.append(f"Comment string is missing explanantion for some tokens: {string}") - continue - - if len(comment_tokens) > len(tokens): - violations.append(f"""Comment string has explanation for extra tokens - that are not a part of the string : {string}""") - continue - - # Validate token format in both string and comment string if it has single token - if len(tokens) < 2: - if "%@" not in tokens[0]: - violations.append(f"String missing correctly formatted token: {string}") - continue - if "%@" not in comment_tokens[0]: - violations.append(f"String comment missing correctly formatted token: {string}") - continue - continue - - # Validate position of both tokens and comment tokens to make sure all placeholder tokens - # in string have corresponding explanation in the comment string - positional_tokens: Set[int] = set() - comment_positional_tokens: Set[int] = set() - - for token in tokens: - if "$" not in token: - violations.append(f"String missing positional tokens: {string}") - continue - - position = int((token.split("$")[0]).replace("%", "")) - - if position in positional_tokens: - violations.append(f"Duplicate token position: {string}") - continue - - positional_tokens.add(position) - - for token in comment_tokens: - if "$" not in token: - violations.append(f"Comment string missing positional tokens: {string}") - continue - - position = int((token.split("$")[0]).replace("%", "")) - - if position in comment_positional_tokens: - violations.append(f"Duplicate comment token position: {string}") - continue - - comment_positional_tokens.add(position) - - for i in range(1, len(tokens) + 1): - if i not in positional_tokens: - violations.append(f"Token position index skipped: {string}") - - for i in range(1, len(comment_tokens) + 1): - if i not in comment_positional_tokens: - violations.append(f"Comment Token position index skipped: {string}") + if len(extra_in_comments) != 0: + violations.append(f"Extra tokens appear in the comment ({extra_in_comments}): {string}") return violations diff --git a/tests/test_placeholder_token_explanation.py b/tests/test_placeholder_token_explanation.py index 23b20bf..1ab7e78 100644 --- a/tests/test_placeholder_token_explanation.py +++ b/tests/test_placeholder_token_explanation.py @@ -61,28 +61,13 @@ def test_placeholder_token_explanation(self): "Key", "This is a string", "Some comment %@ extra token explanation", "en" ), ), - ( - False, - localizationkit.LocalizedString( - "Key", "This is a string with two incorrect positioned tokens %1$@ %3$@", "Some comment %1$@ token explanantion %2$@ token explanantion", "en" - ), - ), - ( - False, - localizationkit.LocalizedString( - "Key", "This is a string with two tokens: %1$@ %2$@", "Some comment with incorrect poistioned token explanantion %1$@ token explanation %3$@ token explanation", "en" - ), - ), ] - for (expected_result, string) in test_cases: + for expected_result, string in test_cases: collection = localizationkit.LocalizedCollection([string]) test = localizationkit.tests.placeholder_token_explanation.PlaceholderTokenExplanation( self.configuration, collection ) result = test.execute() - if expected_result: - self.assertTrue(result.succeeded()) - else: - self.assertFalse(result.succeeded()) + self.assertEqual(expected_result, result.succeeded()) From 7edab040ef1841ca8dee089f1ae74c705e76c99b Mon Sep 17 00:00:00 2001 From: Poonam Baxi Date: Wed, 20 Jan 2021 12:30:32 -0800 Subject: [PATCH 3/4] Nit: fix typo --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6c01b19..d50fb6a 100644 --- a/README.md +++ b/README.md @@ -237,7 +237,7 @@ Check that each token has a position specifier with it. e.g. `%s` is not allowed Identifier: `placeholder_token_explanation` Opt-In: `true` -Checks that if a placeholder is used in a string, the comment explicitly explain what it is replaced with. +Checks that if a placeholder is used in a string, the comment explicitly explains what it is replaced with. Precondition: Each placeholder in the string and its explanation in comment is expected to follow `token_position_identifiers` rule. # Contributing From 0b756c5f46623bc39bf98cfbf4d182e6af0526d8 Mon Sep 17 00:00:00 2001 From: Dale <1363082+dalemyers@users.noreply.github.com> Date: Fri, 22 Jan 2021 13:33:33 +0000 Subject: [PATCH 4/4] Make test opt-in --- localizationkit/tests/placeholder_token_explanation.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/localizationkit/tests/placeholder_token_explanation.py b/localizationkit/tests/placeholder_token_explanation.py index 18cb137..d46fe96 100644 --- a/localizationkit/tests/placeholder_token_explanation.py +++ b/localizationkit/tests/placeholder_token_explanation.py @@ -16,6 +16,10 @@ def name(cls) -> str: def default_settings(cls) -> Dict[str, Any]: return {} + @classmethod + def is_opt_in(cls) -> bool: + return True + def run_test(self) -> List[str]: violations = []