jenkins-bot has submitted this change. ( 
https://gerrit.wikimedia.org/r/c/pywikibot/core/+/297637 )

Change subject: Add wrapper function around wbparsevalue
......................................................................

Add wrapper function around wbparsevalue

Bug: T112140
Change-Id: Ib559b4c9ae541d30866552461e83eefde911ea57
---
M pywikibot/site/_datasite.py
M tests/wikibase_tests.py
2 files changed, 89 insertions(+), 1 deletion(-)

Approvals:
  Xqt: Looks good to me, approved
  jenkins-bot: Verified



diff --git a/pywikibot/site/_datasite.py b/pywikibot/site/_datasite.py
index 5375cc7..b651cd5 100644
--- a/pywikibot/site/_datasite.py
+++ b/pywikibot/site/_datasite.py
@@ -8,7 +8,7 @@
 import json
 import uuid
 from contextlib import suppress
-from typing import Optional
+from typing import Any, Dict, List, Optional
 from warnings import warn

 import pywikibot
@@ -710,6 +710,47 @@
                               total=total, parameters=parameters)
         return gen

+    def parsevalue(self, datatype: str, values: List[str],
+                   options: Dict[str, Any], validate: bool) -> List[Any]:
+        """
+        Send data values to the wikibase parser for interpretation.
+
+        :param datatype: datatype of the values being parsed. Refer to
+            https://www.wikidata.org/w/api.php?action=help&modules=wbparsevalue
+            for a valid datatype.
+        :param values: list of values to be parsed
+        :param options: any additional options for wikibase parser
+            (for time, 'precision' should be specified)
+        :param validate: whether parser should provide data validation as well
+            as parsing
+        :return: list of parsed values
+        :raises ValueError: parsing failed due to some invalid input values
+        """
+        params = {
+            'datatype': datatype,
+            'values': values,
+            'options': json.dumps(options),
+            'validate': validate,
+        }
+        req = self.simple_request(action='wbparsevalue', **params)
+        try:
+            data = req.submit()
+        except APIError as e:
+            if e.code == 'wikibase-parse-error-quantity':
+                raise ValueError(e) from None
+            raise
+        if 'results' not in data:
+            raise ValueError('Parsing via wikibase wbparsevalue failed.')
+
+        results = []
+        for result_hash in data['results']:
+            if 'value' not in result_hash:
+                raise ValueError(
+                    'Parsing via wikibase wbparsevalue failed: {}'
+                    .format(result_hash['error-info']))
+            results.append(result_hash['value'])
+        return results
+
     @need_right('edit')
     def _wbset_action(self, itemdef, action: str, action_data,
                       **kwargs) -> dict:
diff --git a/tests/wikibase_tests.py b/tests/wikibase_tests.py
index 96b7ad6..0ebcb854 100755
--- a/tests/wikibase_tests.py
+++ b/tests/wikibase_tests.py
@@ -630,6 +630,53 @@
             pywikibot.WbMonolingualText(text=None, language='sv')


+class TestWikibaseParser(WikidataTestCase):
+    """Test passing various datatypes to wikibase parser."""
+
+    def test_wbparse_strings(self):
+        """Test that strings return unchanged."""
+        test_list = ['test string', 'second test']
+        parsed_strings = self.site.parsevalue('string', test_list, {}, False)
+        self.assertEqual(parsed_strings, test_list)
+
+    def test_wbparse_time(self):
+        """Test parsing of a time value."""
+        parsed_date = self.site.parsevalue(
+            'time', ['1994-02-08'], {'precision': 9}, False)[0]
+        self.assertEqual(parsed_date['time'], '+1994-02-08T00:00:00Z')
+        self.assertEqual(parsed_date['precision'], 9)
+
+    def test_wbparse_quantity(self):
+        """Test parsing of quantity values."""
+        parsed_quantities = self.site.parsevalue(
+            'quantity',
+            ['1.90e-9+-0.20e-9', '1000000.00000000054321+-0', '-123+-1',
+             '2.70e34+-1e32'], {}, False)
+        self.assertEqual(parsed_quantities[0]['amount'], '+0.00000000190')
+        self.assertEqual(parsed_quantities[0]['upperBound'], '+0.00000000210')
+        self.assertEqual(parsed_quantities[0]['lowerBound'], '+0.00000000170')
+        self.assertEqual(parsed_quantities[1]['amount'],
+                         '+1000000.00000000054321')
+        self.assertEqual(parsed_quantities[1]['upperBound'],
+                         '+1000000.00000000054321')
+        self.assertEqual(parsed_quantities[1]['lowerBound'],
+                         '+1000000.00000000054321')
+        self.assertEqual(parsed_quantities[2]['amount'], '-123')
+        self.assertEqual(parsed_quantities[2]['upperBound'], '-122')
+        self.assertEqual(parsed_quantities[2]['lowerBound'], '-124')
+        self.assertEqual(parsed_quantities[3]['amount'],
+                         '+27000000000000000000000000000000000')
+        self.assertEqual(parsed_quantities[3]['upperBound'],
+                         '+27100000000000000000000000000000000')
+        self.assertEqual(parsed_quantities[3]['lowerBound'],
+                         '+26900000000000000000000000000000000')
+
+    def test_wbparse_raises_valueerror(self):
+        """Test invalid value condition."""
+        with self.assertRaises(ValueError):
+            self.site.parsevalue('quantity', ['Not a quantity'], {}, False)
+
+
 class TestWbGeoShapeNonDry(WbRepresentationTestCase):

     """

--
To view, visit https://gerrit.wikimedia.org/r/c/pywikibot/core/+/297637
To unsubscribe, or for help writing mail filters, visit 
https://gerrit.wikimedia.org/r/settings

Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Change-Id: Ib559b4c9ae541d30866552461e83eefde911ea57
Gerrit-Change-Number: 297637
Gerrit-PatchSet: 14
Gerrit-Owner: ArthurPSmith <[email protected]>
Gerrit-Reviewer: ArthurPSmith <[email protected]>
Gerrit-Reviewer: Matěj Suchánek <[email protected]>
Gerrit-Reviewer: Multichill <[email protected]>
Gerrit-Reviewer: Tobias47n9e <[email protected]>
Gerrit-Reviewer: Xqt <[email protected]>
Gerrit-Reviewer: jenkins-bot
Gerrit-CC: Dvorapa <[email protected]>
Gerrit-MessageType: merged
_______________________________________________
Pywikibot-commits mailing list -- [email protected]
To unsubscribe send an email to [email protected]

Reply via email to