Lokal Profil has uploaded a new change for review.

  https://gerrit.wikimedia.org/r/315645

Change subject: [Not ready] Support adding units to WbQuantity through ItemPage 
or URI
......................................................................

[Not ready] Support adding units to WbQuantity through ItemPage or URI

This should be backwards compatible but will raise a warning for
those useres who used the undocumented feature of providing the
uri to the unit parameter.

entity/_entity is implemented in a similar way to (globe) entity
in Coordinate.

Note that the representation of WbQuantity changes somewhat
(unit='1' -> unit=None), again this is the same difference as in
Coordinate.

Also added more tests for WbQuantity

[Not ready]
'wikibase-conceptbaseuri' was added to siteinfo in
8ef8d6bf9159e5a4cbf9ebfa2286e7599485662b
but is yet to be deployed (hence the dummy need_version values)

Bug: T143594
Change-Id: I027d8878d8d3c45e7294d753db37b92a2a58df65
---
M pywikibot/__init__.py
M pywikibot/page.py
M pywikibot/site.py
M tests/wikibase_edit_tests.py
M tests/wikibase_tests.py
5 files changed, 96 insertions(+), 8 deletions(-)


  git pull ssh://gerrit.wikimedia.org:29418/pywikibot/core 
refs/changes/45/315645/1

diff --git a/pywikibot/__init__.py b/pywikibot/__init__.py
index 70771dd..3b0b798 100644
--- a/pywikibot/__init__.py
+++ b/pywikibot/__init__.py
@@ -255,7 +255,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
@@ -617,25 +617,34 @@
         """
         return format(value, "+g")
 
-    def __init__(self, amount, unit=None, error=None):
+    def __init__(self, amount, unit=None, error=None, entity=''):
         u"""
         Create a new WbQuantity object.
 
         @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
+        @type unit: pywikibot.ItemPage
         @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.
+        @param entity: The URL entity of the Wikibase item for the unit
+        @type entity: str
         """
         if amount is None:
             raise ValueError('no amount given')
-        if unit is None:
-            unit = '1'
+
+        # to maintain backwards compatibility
+        if unit and not isinstance(unit, ItemPage):
+            warning(
+                "WbQuantity now expects 'unit' to be an ItemPage. To go on 
using "
+                "plain entity URIs instead use the 'entity' parameter.")
+            entity = unit
 
         self.amount = self._todecimal(amount)
         self.unit = unit
+        self._entity = entity
 
         if error is None:
             upperError = lowerError = Decimal(0)
@@ -648,6 +657,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.
@@ -658,7 +675,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
 
@@ -675,7 +692,7 @@
         upperBound = cls._todecimal(wb['upperBound'])
         lowerBound = cls._todecimal(wb['lowerBound'])
         error = (upperBound - amount, amount - lowerBound)
-        return cls(amount, wb['unit'], error)
+        return cls(amount, None, error, wb['unit'])
 
 
 class WbMonolingualText(_WbRepresentation):
diff --git a/pywikibot/page.py b/pywikibot/page.py
index 79aefc3..b6cf2d7 100644
--- a/pywikibot/page.py
+++ b/pywikibot/page.py
@@ -3939,6 +3939,11 @@
         data['sitelinks'] = self.sitelinks
         return data
 
+    @pywikibot.site.need_version("x.xx")  #set to correct
+    def concept_url(self):
+        """Return the full URL."""
+        return '{0}{1}'.format(self.site.concept_base_uri, self.id)
+
     def getRedirectTarget(self):
         """Return the redirect target for this page."""
         target = super(ItemPage, self).getRedirectTarget()
diff --git a/pywikibot/site.py b/pywikibot/site.py
index 4a616ef..6d797b3 100644
--- a/pywikibot/site.py
+++ b/pywikibot/site.py
@@ -6992,6 +6992,17 @@
                 '%r does not support entity type "property"'
                 % self)
 
+    @property
+    @need_version("x.xx")  #set to correct
+    def concept_base_uri(self):
+        """
+        Return the base uri for concepts/entities.
+
+        @return: concept base uri
+        @rtype: str
+        """
+        return self.siteinfo['general']['wikibase-conceptbaseuri']
+
     def _get_baserevid(self, claim, baserevid):
         """Check that claim.on_item is set and matches baserevid if used."""
         if not claim.on_item:
diff --git a/tests/wikibase_edit_tests.py b/tests/wikibase_edit_tests.py
index 59bcd29..1ed7732 100644
--- a/tests/wikibase_edit_tests.py
+++ b/tests/wikibase_edit_tests.py
@@ -238,6 +238,23 @@
         claim = item.claims['P271'][0]
         self.assertEqual(claim.getTarget(), target)
 
+    def test_WbQuantity_edit(self):
+        """Attempt adding a monolingual text with valid input."""
+        # Clean the slate in preparation for test."""
+        testsite = self.get_repo()
+        item = self._clean_item(testsite, 'P69')
+
+        # set new claim
+        claim = pywikibot.page.Claim(testsite, 'P69', datatype='quantity')
+        target = pywikibot.WbMonolingualText(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 bdfc4c3..9e88f98 100644
--- a/tests/wikibase_tests.py
+++ b/tests/wikibase_tests.py
@@ -225,7 +225,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_equality(self):
         """Test WbQuantity equality."""
@@ -247,6 +247,34 @@
         """Test WbQuantity error handling."""
         self.assertRaises(ValueError, pywikibot.WbQuantity, amount=None,
                           error=1)
+
+    def test_WbQuantity_entity_unit(self):
+        """Test WbQuantity with uri unit."""
+        q = pywikibot.WbQuantity(amount=1234, error=1,
+                                 
entity='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."""
+        q = pywikibot.WbQuantity(amount=1234, error=1,
+                                 unit=pywikibot.ItemPage(self.get_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."""
@@ -724,6 +752,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.WbMonolingualText(
+            amount=1234, error=1, 
entity='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()

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

Gerrit-MessageType: newchange
Gerrit-Change-Id: I027d8878d8d3c45e7294d753db37b92a2a58df65
Gerrit-PatchSet: 1
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: Lokal Profil <lokal.pro...@gmail.com>

_______________________________________________
MediaWiki-commits mailing list
MediaWiki-commits@lists.wikimedia.org
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits

Reply via email to