예제 #1
0
def _take_screenshot(
        request,
        browser_instance,
        fixture_name,
        session_tmpdir,
        splinter_screenshot_dir,
        splinter_screenshot_getter_html,
        splinter_screenshot_getter_png,
        splinter_screenshot_encoding,
):
    """Capture a screenshot as .png and .html.

    Invoked from session and function browser fixtures.
    """
    slaveoutput = getattr(request.config, 'slaveoutput', None)
    try:
        names = junitxml.mangle_testnames(request.node.nodeid.split("::"))
    except AttributeError:
        # pytest>=2.9.0
        names = junitxml.mangle_test_address(request.node.nodeid)

    classname = '.'.join(names[:-1])
    screenshot_dir = os.path.join(splinter_screenshot_dir, classname)
    screenshot_file_name_format = '{0}.{{format}}'.format(
        '{0}-{1}'.format(names[-1][:128 - len(fixture_name) - 5], fixture_name).replace(os.path.sep, '-')
    )
    screenshot_file_name = screenshot_file_name_format.format(format='png')
    screenshot_html_file_name = screenshot_file_name_format.format(format='html')
    if not slaveoutput:
        if not os.path.exists(screenshot_dir):
            os.makedirs(screenshot_dir)
    else:
        screenshot_dir = session_tmpdir.ensure('screenshots', dir=True).strpath
    screenshot_png_path = os.path.join(screenshot_dir, screenshot_file_name)
    screenshot_html_path = os.path.join(screenshot_dir, screenshot_html_file_name)
    LOGGER.info('Saving screenshot to %s', screenshot_dir)
    try:
        splinter_screenshot_getter_html(browser_instance, screenshot_html_path)
        splinter_screenshot_getter_png(browser_instance, screenshot_png_path)
        if request.node.splinter_failure.longrepr:
            reprtraceback = request.node.splinter_failure.longrepr.reprtraceback
            reprtraceback.extraline = _screenshot_extraline(screenshot_png_path, screenshot_html_path)
        if slaveoutput is not None:
            with codecs.open(screenshot_html_path, encoding=splinter_screenshot_encoding) as html_fd:
                with open(screenshot_png_path, 'rb') as fd:
                    slaveoutput.setdefault('screenshots', []).append({
                        'class_name': classname,
                        'files': [
                            {
                                'file_name': screenshot_file_name,
                                'content': fd.read(),
                            },
                            {
                                'file_name': screenshot_html_file_name,
                                'content': html_fd.read(),
                                'encoding': splinter_screenshot_encoding,
                            }]
                    })
    except Exception as e:  # NOQA
        warnings.warn(pytest.PytestWarning("Could not save screenshot: {0}".format(e)))
예제 #2
0
def _take_screenshot(
        request,
        browser_instance,
        fixture_name,
        session_tmpdir,
        splinter_screenshot_dir,
        splinter_screenshot_getter_html,
        splinter_screenshot_getter_png,
        splinter_screenshot_encoding,
):
    """Capture a screenshot as .png and .html.

    Invoked from session and function browser fixtures.
    """
    slaveoutput = getattr(request.config, 'slaveoutput', None)
    try:
        names = junitxml.mangle_testnames(request.node.nodeid.split("::"))
    except AttributeError:
        # pytest>=2.9.0
        names = junitxml.mangle_test_address(request.node.nodeid)

    classname = '.'.join(names[:-1])
    screenshot_dir = os.path.join(splinter_screenshot_dir, classname)
    screenshot_file_name_format = '{0}.{{format}}'.format(
        '{0}-{1}'.format(names[-1][:128 - len(fixture_name) - 5], fixture_name).replace(os.path.sep, '-')
    )
    screenshot_file_name = screenshot_file_name_format.format(format='png')
    screenshot_html_file_name = screenshot_file_name_format.format(format='html')
    if not slaveoutput:
        if not os.path.exists(screenshot_dir):
            os.makedirs(screenshot_dir)
    else:
        screenshot_dir = session_tmpdir.ensure('screenshots', dir=True).strpath
    screenshot_png_path = os.path.join(screenshot_dir, screenshot_file_name)
    screenshot_html_path = os.path.join(screenshot_dir, screenshot_html_file_name)
    LOGGER.info('Saving screenshot to %s', screenshot_dir)
    try:
        splinter_screenshot_getter_html(browser_instance, screenshot_html_path)
        splinter_screenshot_getter_png(browser_instance, screenshot_png_path)
        if request.node.splinter_failure.longrepr:
            reprtraceback = request.node.splinter_failure.longrepr.reprtraceback
            reprtraceback.extraline = _screenshot_extraline(screenshot_png_path, screenshot_html_path)
        if slaveoutput is not None:
            with codecs.open(screenshot_html_path, encoding=splinter_screenshot_encoding) as html_fd:
                with open(screenshot_png_path, 'rb') as fd:
                    slaveoutput.setdefault('screenshots', []).append({
                        'class_name': classname,
                        'files': [
                            {
                                'file_name': screenshot_file_name,
                                'content': fd.read(),
                            },
                            {
                                'file_name': screenshot_html_file_name,
                                'content': html_fd.read(),
                                'encoding': splinter_screenshot_encoding,
                            }]
                    })
    except Exception as e:  # NOQA
        warnings.warn(pytest.PytestWarning("Could not save screenshot: {0}".format(e)))
예제 #3
0
def test_mangle_test_address():
    from _pytest.junitxml import mangle_test_address

    address = "::".join(
        ["a/my.py.thing.py", "Class", "()", "method", "[a-1-::]"])
    newnames = mangle_test_address(address)
    assert newnames == ["a.my.py.thing", "Class", "method", "[a-1-::]"]
예제 #4
0
def browser_screenshot(
        request, splinter_screenshot_dir, session_tmpdir, splinter_make_screenshot_on_failure,
        splinter_screenshot_encoding, splinter_screenshot_getter_png, splinter_screenshot_getter_html):
    """Make browser screenshot on test failure."""
    yield
    for name, value in request._funcargs.items():
        if hasattr(value, '__splinter_browser__'):
            browser = value
            if splinter_make_screenshot_on_failure and request.node.splinter_failure:
                slaveoutput = getattr(request.config, 'slaveoutput', None)
                try:
                    names = junitxml.mangle_testnames(request.node.nodeid.split("::"))
                except AttributeError:
                    # pytest>=2.9.0
                    names = junitxml.mangle_test_address(request.node.nodeid)

                classname = '.'.join(names[:-1])
                screenshot_dir = os.path.join(splinter_screenshot_dir, classname)
                screenshot_file_name_format = '{0}-{1}.{{format}}'.format(
                    names[-1][:128 - len(name) - 5], name)
                screenshot_file_name = screenshot_file_name_format.format(format='png')
                screenshot_html_file_name = screenshot_file_name_format.format(format='html')
                if not slaveoutput:
                    if not os.path.exists(screenshot_dir):
                        os.makedirs(screenshot_dir)
                else:
                    screenshot_dir = session_tmpdir.ensure('screenshots', dir=True).strpath
                screenshot_png_path = os.path.join(screenshot_dir, screenshot_file_name)
                screenshot_html_path = os.path.join(screenshot_dir, screenshot_html_file_name)
                LOGGER.info('Saving screenshot to %s', screenshot_dir)
                try:
                    splinter_screenshot_getter_html(browser, screenshot_html_path)
                    splinter_screenshot_getter_png(browser, screenshot_png_path)
                    if request.node.splinter_failure.longrepr:
                        reprtraceback = request.node.splinter_failure.longrepr.reprtraceback
                        reprtraceback.extraline = _screenshot_extraline(screenshot_png_path, screenshot_html_path)
                    if slaveoutput is not None:
                        with codecs.open(screenshot_html_path, encoding=splinter_screenshot_encoding) as html_fd:
                            with open(screenshot_png_path) as fd:
                                slaveoutput.setdefault('screenshots', []).append({
                                    'class_name': classname,
                                    'files': [
                                        {
                                            'file_name': screenshot_file_name,
                                            'content': fd.read(),
                                        },
                                        {
                                            'file_name': screenshot_html_file_name,
                                            'content': html_fd.read(),
                                            'encoding': splinter_screenshot_encoding
                                        }]
                                })
                except Exception as e:  # NOQA
                    request.config.warn('SPL504', "Could not save screenshot: {0}".format(e))
예제 #5
0
    def get_test_info(request: FixtureRequest,
                      suffix: str = '',
                      prefix: str = '') -> "TestInfo":
        try:
            names = junitxml.mangle_testnames(
                request.node.nodeid.split("::"))  # type: ignore
        except AttributeError:
            # pytest>=2.9.0
            names = junitxml.mangle_test_address(request.node.nodeid)

        classname = '.'.join(names[:-1])
        test_name = names[-1]
        return TestInfo(test_name, classname)
예제 #6
0
def get_test_info(request, suffix='', prefix=''):
    try:
        names = junitxml.mangle_testnames(request.node.nodeid.split("::"))
    except AttributeError:
        # pytest>=2.9.0
        names = junitxml.mangle_test_address(request.node.nodeid)

    classname = '.'.join(names[:-1])
    test_name = names[-1]
    return {
        'test_name': test_name,
        'classname': classname,
    }
 def record_testreport(self, testreport):
     assert not self.testcase
     names = mangle_test_address(testreport.nodeid)
     classnames = names[:-1]
     if self.xml.prefix:
         classnames.insert(0, self.xml.prefix)
     attrs = {
         "classname": ".".join(classnames),
         "name": bin_xml_escape(names[-1]),
         "file": testreport.location[0],
     }
     if testreport.location[1] is not None:
         attrs["line"] = testreport.location[1]
     if hasattr(testreport, "url"):
         attrs["url"] = testreport.url
     self.attrs = attrs
예제 #8
0
def test_mangle_test_address():
    from _pytest.junitxml import mangle_test_address

    address = "::".join(["a/my.py.thing.py", "Class", "()", "method", "[a-1-::]"])
    newnames = mangle_test_address(address)
    assert newnames == ["a.my.py.thing", "Class", "method", "[a-1-::]"]
예제 #9
0
def _take_screenshot(
    request,
    browser_instance,
    fixture_name,
    session_tmpdir,
    splinter_screenshot_dir,
    splinter_screenshot_getter_html,
    splinter_screenshot_getter_png,
    splinter_screenshot_encoding,
):
    """Capture a screenshot as .png and .html.

    Invoked from session and function browser fixtures.
    """
    slaveoutput = getattr(request.config, "slaveoutput", None)

    names = junitxml.mangle_test_address(request.node.nodeid)

    classname = ".".join(names[:-1])
    screenshot_dir = os.path.join(splinter_screenshot_dir, classname)
    screenshot_file_name_format = "{0}.{{format}}".format("{}-{}".format(
        names[-1][:128 - len(fixture_name) - 5],
        fixture_name).replace(os.path.sep, "-"))
    screenshot_file_name = screenshot_file_name_format.format(format="png")
    screenshot_html_file_name = screenshot_file_name_format.format(
        format="html")
    if not slaveoutput:
        if not os.path.exists(screenshot_dir):
            os.makedirs(screenshot_dir)
    else:
        screenshot_dir = session_tmpdir.ensure("screenshots", dir=True).strpath
    screenshot_png_path = os.path.join(screenshot_dir, screenshot_file_name)
    screenshot_html_path = os.path.join(screenshot_dir,
                                        screenshot_html_file_name)
    LOGGER.info("Saving screenshot to %s", screenshot_dir)
    try:
        splinter_screenshot_getter_html(browser_instance, screenshot_html_path)
        splinter_screenshot_getter_png(browser_instance, screenshot_png_path)
        if request.node.splinter_failure.longrepr:
            reprtraceback = request.node.splinter_failure.longrepr.reprtraceback
            reprtraceback.extraline = _screenshot_extraline(
                screenshot_png_path, screenshot_html_path)
        if slaveoutput is not None:
            with codecs.open(screenshot_html_path,
                             encoding=splinter_screenshot_encoding) as html_fd:
                with open(screenshot_png_path, "rb") as fd:
                    slaveoutput.setdefault("screenshots", []).append({
                        "class_name":
                        classname,
                        "files": [
                            {
                                "file_name": screenshot_file_name,
                                "content": fd.read(),
                            },
                            {
                                "file_name": screenshot_html_file_name,
                                "content": html_fd.read(),
                                "encoding": splinter_screenshot_encoding,
                            },
                        ],
                    })
    except Exception as e:  # NOQA
        warnings.warn(
            pytest.PytestWarning("Could not save screenshot: {}".format(e)))
예제 #10
0
def browser_screenshot(request, splinter_screenshot_dir, session_tmpdir,
                       splinter_make_screenshot_on_failure,
                       splinter_screenshot_encoding,
                       splinter_screenshot_getter_png,
                       splinter_screenshot_getter_html):
    """Make browser screenshot on test failure."""
    yield
    for name, value in request._funcargs.items():
        if hasattr(value, '__splinter_browser__'):
            browser = value
            if splinter_make_screenshot_on_failure and request.node.splinter_failure:
                slaveoutput = getattr(request.config, 'slaveoutput', None)
                try:
                    names = junitxml.mangle_testnames(
                        request.node.nodeid.split("::"))
                except AttributeError:
                    # pytest>=2.9.0
                    names = junitxml.mangle_test_address(request.node.nodeid)

                classname = '.'.join(names[:-1])
                screenshot_dir = os.path.join(splinter_screenshot_dir,
                                              classname)
                screenshot_file_name_format = '{0}-{1}.{{format}}'.format(
                    names[-1][:128 - len(name) - 5], name)
                screenshot_file_name = screenshot_file_name_format.format(
                    format='png')
                screenshot_html_file_name = screenshot_file_name_format.format(
                    format='html')
                if not slaveoutput:
                    if not os.path.exists(screenshot_dir):
                        os.makedirs(screenshot_dir)
                else:
                    screenshot_dir = session_tmpdir.ensure('screenshots',
                                                           dir=True).strpath
                screenshot_png_path = os.path.join(screenshot_dir,
                                                   screenshot_file_name)
                screenshot_html_path = os.path.join(screenshot_dir,
                                                    screenshot_html_file_name)
                LOGGER.info('Saving screenshot to %s', screenshot_dir)
                try:
                    splinter_screenshot_getter_html(browser,
                                                    screenshot_html_path)
                    splinter_screenshot_getter_png(browser,
                                                   screenshot_png_path)
                    if request.node.splinter_failure.longrepr:
                        reprtraceback = request.node.splinter_failure.longrepr.reprtraceback
                        reprtraceback.extraline = _screenshot_extraline(
                            screenshot_png_path, screenshot_html_path)
                    if slaveoutput is not None:
                        with codecs.open(screenshot_html_path,
                                         encoding=splinter_screenshot_encoding
                                         ) as html_fd:
                            with open(screenshot_png_path) as fd:
                                slaveoutput.setdefault(
                                    'screenshots', []).append({
                                        'class_name':
                                        classname,
                                        'files': [{
                                            'file_name': screenshot_file_name,
                                            'content': fd.read(),
                                        }, {
                                            'file_name':
                                            screenshot_html_file_name,
                                            'content':
                                            html_fd.read(),
                                            'encoding':
                                            splinter_screenshot_encoding
                                        }]
                                    })
                except Exception as e:  # NOQA
                    request.config.warn(
                        'SPL504', "Could not save screenshot: {0}".format(e))