Page MenuHomePhabricator

TestSiteSysopWrite.test_protect_exception fails with protect-invalidaction APIError
Closed, ResolvedPublic

Description

pywikibot/data/api/_requests.py:1122: APIError
__________________ TestSiteSysopWrite.test_protect_exception ___________________

self = <tests.site_tests.TestSiteSysopWrite testMethod=test_protect_exception>

    def test_protect_exception(self):
        """Test that site.protect() throws an exception for invalid args."""
        site = self.get_site()
        p1 = pywikibot.Page(site, 'User:Unicodesnowman/ProtectTest')
        with self.assertRaises(AssertionError):
            site.protect(protections={'anInvalidValue': 'sysop'},
>                        page=p1, reason='Pywikibot unit test')

tests/site_tests.py:626: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
pywikibot/site/_decorators.py:93: in callee
    return fn(self, *args, **kwargs)
pywikibot/site/_apisite.py:2792: in protect
    result = req.submit()
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

    def submit(self) -> dict:
        """Submit a query and parse the response.
    
        .. versionchanged:: 8.0.4
           in addition to *readapidenied* also try to login when API
           response is *notloggedin*.
        .. versionchanged:: 9.0
           Raise :exc:`exceptions.APIError` if the same error comes
           twice in a row within the loop.
    
        :return: a dict containing data retrieved from api.php
        """
        self._add_defaults()
        use_get = self._use_get()
        retries = 0
        self.last_error = dict.fromkeys(['code', 'info'])
        while True:
            paramstring = self._http_param_string()
    
            simulate = self._simulate(self.action)
            if simulate:
                return simulate
    
            if self.throttle:
                self.site.throttle(write=self.write)
            else:
                pywikibot.log(
                    f"Submitting unthrottled action '{self.action}'.")
    
            use_get, uri, body, headers = self._get_request_params(use_get,
                                                                   paramstring)
            response, use_get = self._http_request(use_get, uri, body, headers,
                                                   paramstring)
            if response is None:
                continue
    
            result = self._json_loads(response)
            if result is None:
                continue
    
            if self._userinfo_query(result):
                continue
    
            if self._handle_warnings(result):
                continue
    
            if 'error' not in result:
                return result
    
            error = result['error']
            for key in result:
                if key in ('error', 'warnings'):
                    continue
                assert key not in error
                error[key] = result[key]
    
            if '*' in error:
                # help text returned
                error['help'] = error.pop('*')
            code = error.setdefault('code', 'Unknown')
            info = error.setdefault('info', None)
    
            if (code == self.last_error['code']
                    and info == self.last_error['info']):
                raise pywikibot.exceptions.APIError(**self.last_error)
            self.last_error = error
    
            if not self._logged_in(code):
                continue
    
            if code == 'maxlag':
                retries += 1
                if retries > max(5, pywikibot.config.max_retries):
                    break
                pywikibot.log('Pausing due to database lag: ' + info)
    
                try:
                    lag = error['lag']
                except KeyError:
                    lag = lagpattern.search(info)
                    lag = float(lag['lag']) if lag else 0.0
    
                self.site.throttle.lag(lag * retries)
                # reset last error
                self.last_error = dict.fromkeys(['code', 'info'])
                continue
    
            if code == 'help' and self.action == 'help':
                # The help module returns an error result with the complete
                # API information. As this data was requested, return the
                # data instead of raising an exception.
                return {'help': {'mime': 'text/plain',
                                 'help': error['help']}}
    
            pywikibot.warning(f'API error {code}: {info}')
            pywikibot.log(f'           headers=\n{response.headers}')
    
            if self._internal_api_error(code, error.copy(), result):
                continue
    
            # Phab. tickets T48535, T64126, T68494, T68619
            if code == 'failed-save' \
               and self._is_wikibase_error_retryable(error):
                self.wait()
                continue
    
            if code == 'ratelimited':
                self._ratelimited()
                continue
    
            # If notloggedin or readapidenied is returned try to login
            if code in ('notloggedin', 'readapidenied') \
               and self.site._loginstatus in (LoginStatus.NOT_ATTEMPTED,
                                              LoginStatus.NOT_LOGGED_IN):
                self.site.login()
                continue
    
            if self._bad_token(code):
                continue
    
            if 'mwoauth-invalid-authorization' in code:
                msg = f'OAuth authentication for {self.site}: {info}'
                if 'Nonce already used' in info:
                    pywikibot.error(f'Retrying failed {msg}')
                    continue
                raise NoUsernameError(f'Failed {msg}')
    
            if code == 'cirrussearch-too-busy-error':  # T170647
                self.wait()
                continue
    
            if code in ('search-title-disabled', 'search-text-disabled'):
                prefix = 'gsr' if 'gsrsearch' in self._params else 'sr'
                del self._params[prefix + 'what']
                # use intitle: search instead
                if code == 'search-title-disabled' \
                   and self.site.has_extension('CirrusSearch'):
                    key = prefix + 'search'
                    self._params[key] = ['intitle:' + search
                                         for search in self._params[key]]
                continue
    
            if code == 'urlshortener-blocked':  # T244062
                # add additional informations to error dict
                error['current site'] = self.site
                if self.site.user():
                    error['current user'] = self.site.user()
                else:  # not logged in; show the IP
                    uinfo = self.site.userinfo
                    error['current user'] = uinfo['name']
    
            # raise error
            try:
                param_repr = str(self._params)
                pywikibot.log(
                    f'API Error: query=\n{pprint.pformat(param_repr)}')
                pywikibot.log(f'           response=\n{result}')
    
                args = {'param': body} if body else {}
                args.update(error)
>               raise pywikibot.exceptions.APIError(**args)
E               pywikibot.exceptions.APIError: protect-invalidaction: Invalid protection type "anInvalidValue".
E               [param: action=protect&title=User%3AUnicodesnowman%2FProtectTest&protections=anInvalidValue%3Dsysop&reason=Pywikibot+unit+test&assert=user&maxlag=5&format=json&token=f415c10722e8c04f738cc5e911d7995966682142%2B%5C;
E                servedby: mw-api-ext.eqiad.main-5c9cc4cfcf-s2wdv;
E                help: See https://test.wikipedia.org/w/api.php for API usage. Subscribe to the mediawiki-api-announce mailing list at &lt;https://lists.wikimedia.org/postorius/lists/mediawiki-api-announce.lists.wikimedia.org/&gt; for notice of API deprecations and breaking changes.]

Event Timeline

Xqt triaged this task as High priority.Jun 11 2024, 2:08 PM

Change #1041667 had a related patch set uploaded (by Xqt; author: Xqt):

[pywikibot/core@master] [fix] Fix TestSiteSysopWrite.test_protect_exception

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

Change #1041667 merged by jenkins-bot:

[pywikibot/core@master] [fix] Fix TestSiteSysopWrite.test_protect_exception

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