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

Change subject: Add support for geo-shape Wikibase data type
......................................................................

Add support for geo-shape Wikibase data type

Introduces the WbGeoShape class to provide handling of geo-shape
data and do some basic validation on indata.

Bug:T161726
Change-Id: Ia96d35519163307227159ccece5981783ce8b558
---
M pywikibot/__init__.py
M pywikibot/page.py
M tests/wikibase_edit_tests.py
M tests/wikibase_tests.py
4 files changed, 154 insertions(+), 1 deletion(-)


  git pull ssh://gerrit.wikimedia.org:29418/pywikibot/core 
refs/changes/00/346700/1

diff --git a/pywikibot/__init__.py b/pywikibot/__init__.py
index 273e538..899a532 100644
--- a/pywikibot/__init__.py
+++ b/pywikibot/__init__.py
@@ -809,6 +809,72 @@
         """
         return cls(wb['text'], wb['language'])
 
+
+class WbGeoShape(_WbRepresentation):
+    """
+    A Wikibase geo-shape representation.
+
+    A temporary implementation until T162336 has been resolved.
+    """
+
+    _items = ('page', )
+
+    def __init__(self, page, site=None):
+        """
+        Create a new WbGeoShape object.
+
+        @param page: page containing the map data
+        @type text: pywikibot.Page
+        @param site: The Wikibase site
+        @type site: pywikibot.site.DataSite
+        """
+        site = site or Site()
+        if not isinstance(page, Page):
+            raise ValueError('page must be a pywikibot.Page object.')
+
+        # validate page exists
+        if not page.exists():
+            raise ValueError('page must exist.')
+
+        # validate page is on the right site
+        media_site = site.image_repository()
+        if page.site != media_site:
+            raise ValueError('page must be on the image repository site.')
+
+        # validate page title fulfills hard-coded Wikibase requirement
+        # pcre regexp: '/^Data:[^\\[\\]#\\\:{|}]+\.map$/u'
+        # As we have already checked for existence the following simplified
+        # check should be enough.
+        if not page.title().startswith('Data:') or \
+                not page.title().endswith('.map'):
+            raise ValueError(
+                "page must be a '.map' page in the 'Data:' namespace.")
+
+        self.page = page
+
+    def toWikibase(self):
+        """
+        Convert the data to a JSON object for the Wikibase API.
+
+        @return: Wikibase JSON
+        @rtype: str
+        """
+        return self.page.title()
+
+    @classmethod
+    def fromWikibase(cls, page_name, site):
+        """
+        Create a WbGeoShape from the JSON data given by the Wikibase API.
+
+        @param page_name: page name from Wikibase value
+        @type page_name: str
+        @rtype: pywikibot.WbGeoShape
+        """
+        media_site = site.image_repository()
+        page = Page(media_site, page_name)
+        return cls(page)
+
+
 _sites = {}
 _url_cache = {}  # The code/fam pair for each URL
 
diff --git a/pywikibot/page.py b/pywikibot/page.py
index 0299b5c..d9634b3 100644
--- a/pywikibot/page.py
+++ b/pywikibot/page.py
@@ -4316,6 +4316,7 @@
              'monolingualtext': pywikibot.WbMonolingualText,
              'math': basestring,
              'external-id': basestring,
+             'geo-shape': pywikibot.WbGeoShape,
              }
 
     value_types = {'wikibase-item': 'wikibase-entityid',
@@ -4325,6 +4326,7 @@
                    'globe-coordinate': 'globecoordinate',
                    'math': 'string',
                    'external-id': 'string',
+                   'geo-shape': 'string',
                    }
 
     def __init__(self, site, id, datatype=None):
@@ -4457,6 +4459,7 @@
         'commonsMedia': lambda value, site:
             FilePage(pywikibot.Site('commons', 'commons'), value),
         'globe-coordinate': pywikibot.Coordinate.fromWikibase,
+        'geo-shape': pywikibot.WbGeoShape.fromWikibase,
         'time': lambda value, site: pywikibot.WbTime.fromWikibase(value),
         'quantity': pywikibot.WbQuantity.fromWikibase,
         'monolingualtext': lambda value, site:
diff --git a/tests/wikibase_edit_tests.py b/tests/wikibase_edit_tests.py
index 670eab9..1361c98 100644
--- a/tests/wikibase_edit_tests.py
+++ b/tests/wikibase_edit_tests.py
@@ -300,6 +300,25 @@
         claim = item.claims['P718'][0]
         self.assertEqual(claim.getTarget(), target)
 
+    def test_WbGeoShape_edit(self):
+        """Attempt adding a geo-shape with valid input."""
+        # Clean the slate in preparation for test.
+        testsite = self.get_repo()
+        item = self._clean_item(testsite, 'P27199')
+
+        # set new claim
+        claim = pywikibot.page.Claim(testsite, 'P27199', datatype='geo-shape')
+        commons_site = pywikibot.Site('commons', 'commons')
+        page = pywikibot.Page(commons_site, 'Data:Lyngby Hovedgade.map')
+        target = pywikibot.WbGeoShape(page)
+        claim.setTarget(target)
+        item.addClaim(claim)
+
+        # confirm new claim
+        item.get(force=True)
+        claim = item.claims['P27199'][0]
+        self.assertEqual(claim.getTarget(), target)
+
 
 class TestWikibaseRemoveQualifier(WikibaseTestCase):
 
diff --git a/tests/wikibase_tests.py b/tests/wikibase_tests.py
index 79a70d8..1a24f78 100644
--- a/tests/wikibase_tests.py
+++ b/tests/wikibase_tests.py
@@ -18,7 +18,7 @@
 import pywikibot
 
 from pywikibot import pagegenerators
-from pywikibot.page import WikibasePage, ItemPage, PropertyPage
+from pywikibot.page import WikibasePage, ItemPage, PropertyPage, Page
 from pywikibot.site import Namespace, NamespacesDict
 from pywikibot.tools import MediaWikiVersion
 
@@ -490,6 +490,71 @@
                           text=None, language='sv')
 
 
+class TestWbGeoShapeNonDry(WikidataTestCase):
+
+    """
+    Test Wikibase WbGeoShape data type (non-dry).
+
+    These require non dry tests due to the page.exists() call.
+    """
+
+    def setUp(self):
+        self.commons = pywikibot.Site('commons', 'commons')
+        self.page = Page(self.commons, 'Data:Lyngby Hovedgade.map')
+        super(TestWbGeoShapeNonDry, self).setUp()
+
+    def test_WbGeoShape_page(self):
+        """Test WbGeoShape page."""
+        q = pywikibot.WbGeoShape(self.page)
+        q_val = u'Data:Lyngby Hovedgade.map'
+        self.assertEqual(q.toWikibase(), q_val)
+
+    def test_WbGeoShape_page_and_site(self):
+        """Test WbGeoShape from page and site."""
+        q = pywikibot.WbGeoShape(self.page, self.get_repo())
+        q_val = u'Data:Lyngby Hovedgade.map'
+        self.assertEqual(q.toWikibase(), q_val)
+
+    def test_WbGeoShape_equality(self):
+        """Test WbGeoShape equality."""
+        q = pywikibot.WbGeoShape(self.page, self.get_repo())
+        self.assertEqual(q, q)
+
+    def test_WbGeoShape_fromWikibase(self):
+        """Test WbGeoShape.fromWikibase() instantiating."""
+        repo = self.get_repo()
+        q = pywikibot.WbGeoShape.fromWikibase(
+            'Data:Lyngby Hovedgade.map', repo)
+        self.assertEqual(q.toWikibase(), 'Data:Lyngby Hovedgade.map')
+
+    def test_WbGeoShape_error_on_non_page(self):
+        """Test WbGeoShape error handling when given a non-page."""
+        self.assertRaises(ValueError, pywikibot.WbGeoShape,
+                          'A string', self.get_repo())
+
+    def test_WbGeoShape_error_on_non_exitant_page(self):
+        """Test WbGeoShape error handling of a non-existant page."""
+        page = Page(self.commons, 'Non-existant page... really')
+        self.assertRaises(ValueError, pywikibot.WbGeoShape,
+                          page, self.get_repo())
+
+    def test_WbGeoShape_error_on_wrong_site(self):
+        """Test WbGeoShape error handling of a page on non-filerepo site."""
+        repo = self.get_repo()
+        page = Page(repo, 'Q123')
+        self.assertRaises(ValueError, pywikibot.WbGeoShape,
+                          page, self.get_repo())
+
+    def test_WbGeoShape_error_on_wrong_page_type(self):
+        """Test WbGeoShape error handling of a non-map page."""
+        non_data_page = Page(self.commons, 'File:Foo.jpg')
+        non_map_page = Page(self.commons, 'Data:Templatedata/Graph:Lines.tab')
+        self.assertRaises(ValueError, pywikibot.WbGeoShape,
+                          non_data_page, self.get_repo())
+        self.assertRaises(ValueError, pywikibot.WbGeoShape,
+                          non_map_page, self.get_repo())
+
+
 class TestItemPageExtensibility(TestCase):
 
     """Test ItemPage extensibility."""

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

Gerrit-MessageType: newchange
Gerrit-Change-Id: Ia96d35519163307227159ccece5981783ce8b558
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