Lokal Profil has uploaded a new change for review. ( 
https://gerrit.wikimedia.org/r/334908 )

Change subject: Support adding units to WbQuantity through ItemPage or entity 
url
......................................................................

Support adding units to WbQuantity through ItemPage or entity url

This is be backwards compatible so either ItemPages or entity
urls may be provided as units.

Provided urls are not validated (outside of limiting it to the
http(s) protocols) since items need not be in the same repo as the
claim.

Note that the internal representation of WbQuantity changes somewhat
(unit='1' -> unit=None), since '1' encodes "no unit" in Wikibase.

This commit replaces the following two:
Icdcfed92df7734d5162c432a2c6d3d00a1526491
Ibc05165841df8c1ef3108a55dc53bfcbe09da35d

Bug: T143594
Change-Id: I0ef7249d7a8f31ab62aa57d4f661062e889d9585
---
M pywikibot/__init__.py
M tests/wikibase_edit_tests.py
M tests/wikibase_tests.py
3 files changed, 96 insertions(+), 9 deletions(-)


  git pull ssh://gerrit.wikimedia.org:29418/pywikibot/core 
refs/changes/08/334908/1

diff --git a/pywikibot/__init__.py b/pywikibot/__init__.py
index 42b93ec..679eca9 100644
--- a/pywikibot/__init__.py
+++ b/pywikibot/__init__.py
@@ -256,7 +256,7 @@
         @type dim: int
         @param site: The Wikibase site
         @type site: pywikibot.site.DataSite
-        @param entity: The URL entity of a Wikibase item
+        @param entity: The URL entity of a Wikibase item for the globe
         @type entity: str
         """
         self.lat = lat
@@ -651,7 +651,9 @@
         @param amount: number representing this quantity
         @type amount: string or Decimal. Other types are accepted, and 
converted
                       via str to Decimal.
-        @param unit: not used (only unit-less quantities are supported)
+        @param unit: the Wikibase item for the unit or the URL entity of this
+                     Wikibase item.
+        @type unit: pywikibot.ItemPage, str or None
         @param error: the uncertainty of the amount (e.g. ±1)
         @type error: same as amount, or tuple of two values, where the first 
value is
                      the upper error and the second is the lower error value.
@@ -660,11 +662,17 @@
         """
         if amount is None:
             raise ValueError('no amount given')
-        if unit is None:
-            unit = '1'
 
         self.amount = self._todecimal(amount)
         self.unit = unit
+        self._entity = None
+
+        # also allow entity urls to be provided via unit parameter
+        if unit and not isinstance(unit, ItemPage):
+            if unit.split('://')[0] in ('http', 'https'):
+                self._entity = unit
+            else:
+                raise ValueError("'unit' must be an ItemPage or entity url.")
 
         if error is None and not self._require_errors(site):
             self.upperBound = self.lowerBound = None
@@ -680,6 +688,14 @@
             self.upperBound = self.amount + upperError
             self.lowerBound = self.amount - lowerError
 
+    @property
+    def entity(self):
+        if self._entity:
+            return self._entity
+        if self.unit:
+            return self.unit.concept_url()
+        return '1'
+
     def toWikibase(self):
         """
         Convert the data to a JSON object for the Wikibase API.
@@ -690,7 +706,7 @@
         json = {'amount': self._fromdecimal(self.amount),
                 'upperBound': self._fromdecimal(self.upperBound),
                 'lowerBound': self._fromdecimal(self.lowerBound),
-                'unit': self.unit
+                'unit': self.entity
                 }
         return json
 
@@ -709,7 +725,11 @@
         error = None
         if (upperBound and lowerBound) or cls._require_errors(site):
             error = (upperBound - amount, amount - lowerBound)
-        return cls(amount, wb['unit'], error, site)
+        if wb['unit'] == '1':
+            unit = None
+        else:
+            unit = wb['unit']
+        return cls(amount, unit, error, site)
 
 
 class WbMonolingualText(_WbRepresentation):
diff --git a/tests/wikibase_edit_tests.py b/tests/wikibase_edit_tests.py
index 621146b..3a24239 100644
--- a/tests/wikibase_edit_tests.py
+++ b/tests/wikibase_edit_tests.py
@@ -224,7 +224,7 @@
 
     def test_WbMonolingualText_edit(self):
         """Attempt adding a monolingual text with valid input."""
-        # Clean the slate in preparation for test."""
+        # Clean the slate in preparation for test.
         testsite = self.get_repo()
         item = self._clean_item(testsite, 'P271')
 
@@ -245,7 +245,7 @@
         testsite = self.get_repo()
         item = self._clean_item(testsite, 'P69')
 
-        # Make sure the wiki supports wikibase-conceptbaseuri
+        # Make sure the wiki supports unbound uncertainties
         if MediaWikiVersion(testsite.version()) < 
MediaWikiVersion('1.29.0-wmf.2'):
             raise unittest.SkipTest('Wiki version must be 1.29.0-wmf.2 or '
                                     'newer to support unbound uncertainties.')
@@ -261,6 +261,28 @@
         claim = item.claims['P69'][0]
         self.assertEqual(claim.getTarget(), target)
 
+    def test_WbQuantity_edit(self):
+        """Attempt adding a quantity with valid input."""
+        # Clean the slate in preparation for test.
+        testsite = self.get_repo()
+        item = self._clean_item(testsite, 'P69')
+
+        # Make sure the wiki supports wikibase-conceptbaseuri
+        if MediaWikiVersion(testsite.version()) < 
MediaWikiVersion('1.28-wmf.23'):
+            raise unittest.SkipTest('Wiki version must be 1.28-wmf.23 or '
+                                    'newer to expose wikibase-conceptbaseuri.')
+
+        # set new claim
+        claim = pywikibot.page.Claim(testsite, 'P69', datatype='quantity')
+        target = pywikibot.WbQuantity(amount=1234, error=1, unit=item)
+        claim.setTarget(target)
+        item.addClaim(claim)
+
+        # confirm new claim
+        item.get(force=True)
+        claim = item.claims['P69'][0]
+        self.assertEqual(claim.getTarget(), target)
+
     def test_identifier_edit(self):
         """Attempt adding a math claim with valid input."""
         testsite = self.get_repo()
diff --git a/tests/wikibase_tests.py b/tests/wikibase_tests.py
index 8a18771..fa1019c 100644
--- a/tests/wikibase_tests.py
+++ b/tests/wikibase_tests.py
@@ -237,7 +237,7 @@
         self.assertEqual("%r" % q,
                          "WbQuantity(amount=%(val)s, "
                          "upperBound=%(val)s, lowerBound=%(val)s, "
-                         "unit=1)" % {'val': '0.044405586'})
+                         "unit=None)" % {'val': '0.044405586'})
 
     def test_WbQuantity_formatting_unbound(self):
         """Test WbQuantity formatting without bounds."""
@@ -291,6 +291,39 @@
         """Test WbQuantity error handling."""
         self.assertRaises(ValueError, pywikibot.WbQuantity, amount=None,
                           error=1)
+
+    def test_WbQuantity_entity_unit(self):
+        """Test WbQuantity with entity url unit."""
+        q = pywikibot.WbQuantity(amount=1234, error=1,
+                                 unit='http://www.wikidata.org/entity/Q712226')
+        self.assertEqual(q.toWikibase(),
+                         {'amount': '+1234', 'lowerBound': '+1233',
+                          'upperBound': '+1235',
+                          'unit': 'http://www.wikidata.org/entity/Q712226', })
+
+    def test_WbQuantity_ItemPage_unit(self):
+        """Test WbQuantity with ItemPage unit."""
+        repo = self.get_repo()
+        if MediaWikiVersion(repo.version()) < MediaWikiVersion('1.28-wmf.23'):
+            raise unittest.SkipTest('Wiki version must be 1.28-wmf.23 or '
+                                    'newer to expose wikibase-conceptbaseuri.')
+
+        q = pywikibot.WbQuantity(amount=1234, error=1,
+                                 unit=pywikibot.ItemPage(repo, 'Q712226'))
+        self.assertEqual(q.toWikibase(),
+                         {'amount': '+1234', 'lowerBound': '+1233',
+                          'upperBound': '+1235',
+                          'unit': 'http://www.wikidata.org/entity/Q712226', })
+
+    def test_WbQuantity_unit_fromWikibase(self):
+        """Test WbQuantity recognising unit from Wikibase output."""
+        q = pywikibot.WbQuantity.fromWikibase({
+            'amount': '+1234', 'lowerBound': '+1233', 'upperBound': '+1235',
+            'unit': 'http://www.wikidata.org/entity/Q712226', })
+        self.assertEqual(q.toWikibase(),
+                         {'amount': '+1234', 'lowerBound': '+1233',
+                          'upperBound': '+1235',
+                          'unit': 'http://www.wikidata.org/entity/Q712226', })
 
     def test_WbMonolingualText_string(self):
         """Test WbMonolingualText string."""
@@ -789,6 +822,16 @@
         claim.setTarget(target)
         self.assertEqual(claim.target, target)
 
+    def test_set_WbQuantity(self):
+        """Test setting claim of quantity type."""
+        wikidata = self.get_repo()
+        claim = pywikibot.Claim(wikidata, 'P1106')
+        self.assertEqual(claim.type, 'quantity')
+        target = pywikibot.WbQuantity(
+            amount=1234, error=1, 
unit='http://www.wikidata.org/entity/Q712226')
+        claim.setTarget(target)
+        self.assertEqual(claim.target, target)
+
     def test_set_math(self):
         """Test setting claim of math type."""
         wikidata = self.get_repo()
@@ -824,6 +867,8 @@
         self.assertRaises(ValueError, url_claim.setTarget, 
pywikibot.WbTime(2001, site=wikidata))
         mono_claim = pywikibot.Claim(wikidata, 'P1450')
         self.assertRaises(ValueError, mono_claim.setTarget, 'foo')
+        quantity_claim = pywikibot.Claim(wikidata, 'P1106')
+        self.assertRaises(ValueError, quantity_claim.setTarget, 'foo')
 
 
 class TestItemBasePageMethods(WikidataTestCase, BasePageMethodsTestBase):

-- 
To view, visit https://gerrit.wikimedia.org/r/334908
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings

Gerrit-MessageType: newchange
Gerrit-Change-Id: I0ef7249d7a8f31ab62aa57d4f661062e889d9585
Gerrit-PatchSet: 1
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: Lokal Profil <[email protected]>

_______________________________________________
MediaWiki-commits mailing list
[email protected]
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits

Reply via email to