Exemplo n.º 1
0
def svalid(arg):
    '''Validate the passing in string to be valid HTML.  Returns True
	if the string is valid, otherwise raises the InvalidHTML exception.'''

    if _QUICK:
        return True

    with tempfile.NamedTemporaryFile() as fp:
        fp.write(arg)
        fp.flush()

        i = Validator().validate([fp.name])

        if i:
            raise InvalidHTML('%d errors' % i)

    return True
Exemplo n.º 2
0
    def validate(
        self,
        # The relative URL to validate.
        url,
        # An optional string that, if provided, must be in the text returned by the server. If this is a sequence of strings, all of the provided strings must be in the text returned by the server.
        expected_string="",
        # The number of validation errors expected. If None, no validation is performed.
        expected_errors=None,
        # The expected status code from the request.
        expected_status=200,
        # All additional keyword arguments are passed to the ``post`` method.
        **kwargs,
    ):

        try:
            try:
                self.post(url, **kwargs)
            except HTTPError as e:
                # If this was the expected result, return.
                if e.code == expected_status:
                    # Since this is an error of some type, these paramets must be empty, since they can't be checked.
                    assert not expected_string
                    assert not expected_errors
                    return ""
                else:
                    raise
            assert self.status == expected_status
            if expected_string:
                if isinstance(expected_string, str):
                    assert expected_string in self.text
                else:
                    # Assume ``expected_string`` is a sequence of strings.
                    assert all(string in self.text
                               for string in expected_string)

            if expected_errors is not None and not self.pytestconfig.getoption(
                    "skip_w3_validate"):

                # Redo this section using html5validate command line
                vld = Validator(errors_only=True, stack_size=2048)
                tmpname = self.tmp_path / "tmphtml.html"
                with open(tmpname, "w", encoding="utf8") as f:
                    f.write(self.text)
                errors = vld.validate([str(tmpname)])

                assert errors <= expected_errors

            return self.text

        except AssertionError:
            # Save the HTML to make fixing the errors easier. Note that ``self.text`` is already encoded as utf-8.
            validation_file = url.replace("/", "-") + ".html"
            with open(validation_file, "wb") as f:
                f.write(_html_prep(self.text))
            print("Validation failure saved to {}.".format(validation_file))
            raise

        except RuntimeError as e:
            # Provide special handling for web2py exceptions by saving the
            # resulting traceback.
            if e.args[0].startswith("ticket "):
                # Create a client to access the admin interface.
                admin_client = WebClient("{}/admin/".format(
                    self.web2py_server_address),
                                         postbacks=True)
                # Log in.
                admin_client.post(
                    "", data={"password": self.web2py_server.password})
                assert admin_client.status == 200
                # Get the error.
                error_code = e.args[0][len("ticket "):]
                admin_client.get("default/ticket/" + error_code)
                assert admin_client.status == 200
                # Save it to a file.
                traceback_file = ("".join(c if c not in r"\/:*?<>|" else "_"
                                          for c in url) + "_traceback.html")
                with open(traceback_file, "wb") as f:
                    f.write(_html_prep(admin_client.text))
                print("Traceback saved to {}.".format(traceback_file))
            raise
Exemplo n.º 3
0
    def validate(self,
        # The relative URL to validate.
        url,
        # An optional string that, if provided, must be in the text returned by the server. If this is a sequence of strings, all of the provided strings must be in the text returned by the server.
        expected_string='',
        # The number of validation errors expected. If None, no validation is performed.
        expected_errors=None,
        # The expected status code from the request.
        expected_status=200,
        # All additional keyword arguments are passed to the ``post`` method.
        **kwargs):

        try:
            try:
                self.post(url, **kwargs)
            except HTTPError as e:
                # If this was the expected result, return.
                if e.code == expected_status:
                    # Since this is an error of some type, these paramets must be empty, since they can't be checked.
                    assert not expected_string
                    assert not expected_errors
                    return ''
                else:
                    raise
            assert self.status == expected_status
            if expected_string:
                if isinstance(expected_string, str):
                    assert expected_string in self.text
                else:
                    # Assume ``expected_string`` is a sequence of strings.
                    assert all(string in self.text for string in expected_string)

            if expected_errors is not None and W3_VALIDATE:
                # Redo this section using html5validate command line
                vld = Validator(errors_only=True)
                tmpname = self.tmp_path / 'tmphtml.html'
                with open(tmpname, 'w') as f:
                    f.write(self.text)
                errors = vld.validate([tmpname])

                assert errors == expected_errors

            return self.text

        except AssertionError:
            # Save the HTML to make fixing the errors easier. Note that ``self.text`` is already encoded as utf-8.
            validation_file = url.replace('/', '-') + '.html'
            with open(validation_file, 'wb') as f:
                f.write(_html_prep(self.text))
            print('Validation failure saved to {}.'.format(validation_file))
            raise

        except RuntimeError as e:
            # Provide special handling for web2py exceptions by saving the
            # resulting traceback.
            if e.args[0].startswith('ticket '):
                # Create a client to access the admin interface.
                admin_client = WebClient('{}/admin/'.format(self.web2py_server_address),
                                         postbacks=True)
                # Log in.
                admin_client.post('', data={'password':
                                            self.web2py_server.password})
                assert admin_client.status == 200
                # Get the error.
                error_code = e.args[0][len('ticket '):]
                admin_client.get('default/ticket/' + error_code)
                assert admin_client.status == 200
                # Save it to a file.
                traceback_file = url.replace('/', '-') + '_traceback.html'
                with open(traceback_file, 'wb') as f:
                    f.write(_html_prep(admin_client.text))
                print('Traceback saved to {}.'.format(traceback_file))
            raise