Example #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)))
Example #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)))
Example #3
0
def browser_screenshot(request, splinter_screenshot_dir):
    """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)
                names = junitxml.mangle_testnames(request.node.nodeid.split("::"))
                classname = '.'.join(names[:-1])
                screenshot_dir = os.path.join(splinter_screenshot_dir, classname)
                screenshot_file_name = '{0}-{1}.png'.format(
                    names[-1][:128 - len(name) - 5], name)
                if not slaveoutput:
                    if not os.path.exists(screenshot_dir):
                        os.makedirs(screenshot_dir)
                else:
                    screenshot_dir = session_tmpdir.mkdir('screenshots').strpath
                screenshot_path = os.path.join(screenshot_dir, screenshot_file_name)
                LOGGER.info('Saving screenshot to {0}'.format(screenshot_path))
                try:
                    browser.driver.save_screenshot(screenshot_path)
                    with open(screenshot_path) as fd:
                        if slaveoutput is not None:
                            slaveoutput.setdefault('screenshots', []).append({
                                'class_name': classname,
                                'file_name': screenshot_file_name,
                                'content': fd.read()
                            })
                except Exception as e:
                    request.config.warn('SPL504', "Could not save screenshot: {0}".format(e))
Example #4
0
    def pytest_runtest_protocol(self, __multicall__, item, nextitem):
        if not self.testsuite:
            module = parent_module(item)
            self.impl.start_suite(name='.'.join(mangle_testnames(module.nodeid.split("::"))),
                                  description=module.module.__doc__ or None)
            self.testsuite = 'Yes'

        name = '.'.join(mangle_testnames([x.name for x in parent_down_from_module(item)]))
        self.impl.start_case(name, description=item.function.__doc__, labels=labels_of(item))
        result = __multicall__.execute()

        if not nextitem or parent_module(item) != parent_module(nextitem):
            self.impl.stop_suite()
            self.testsuite = None

        return result
Example #5
0
def browser_screenshot(request, screenshot_dir, make_screenshot_on_failure):
    """
    Make browser screenshot on test failure.
    """
    yield
    if not (make_screenshot_on_failure and
            getattr(request.node, 'selenium_failure', None)):
        return
    for name, value in request._funcargs.items():
        # find instance of webdriver in function args
        if isinstance(getattr(value, '__factory__', None), DriverFactory):
            browser = value
            names = junitxml.mangle_testnames(request.node.nodeid.split("::"))
            classname = '.'.join(names[:-1])
            screenshot_dir = os.path.join(screenshot_dir, classname)
            screenshot_file_name = '{0}-{1}.png'.format(
                names[-1][:128 - len(name) - 5], name
            )
            if not os.path.exists(screenshot_dir):
                os.makedirs(screenshot_dir)
            screenshot_path = \
                os.path.join(screenshot_dir, screenshot_file_name)
            try:
                browser.__factory__.save_screenshot(browser, screenshot_path)
            except Exception as e:
                request.config.warn(
                    'SPL504', "Could not save screenshot: %s" % e
                )
Example #6
0
 def make_screenshot_on_failure():
     if splinter_make_screenshot_on_failure and request.node.splinter_failure:
         slaveoutput = getattr(request.config, 'slaveoutput', None)
         names = junitxml.mangle_testnames(
             request.node.nodeid.split("::"))
         classname = '.'.join(names[:-1])
         screenshot_dir = os.path.join(splinter_screenshot_dir,
                                       classname)
         screenshot_file_name = '{0}-{1}.png'.format(
             names[-1][:128 - len(parent.__name__) - 5],
             parent.__name__)
         if not slaveoutput:
             if not os.path.exists(screenshot_dir):
                 os.makedirs(screenshot_dir)
         else:
             screenshot_dir = tmpdir.mkdir('screenshots').strpath
         screenshot_path = os.path.join(screenshot_dir,
                                        screenshot_file_name)
         browser.driver.save_screenshot(screenshot_path)
         with open(screenshot_path) as fd:
             if slaveoutput is not None:
                 slaveoutput.setdefault('screenshots', []).append({
                     'class_name':
                     classname,
                     'file_name':
                     screenshot_file_name,
                     'content':
                     fd.read()
                 })
Example #7
0
    def pytest_runtest_protocol(self, item, nextitem):
        try:
            # for common items
            description = item.function.__doc__
        except AttributeError:
            # for doctests that has no `function` attribute
            description = item.reportinfo()[2]
        self.test = TestCase(
            name='.'.join(
                mangle_testnames(
                    [x.name for x in parent_down_from_module(item)])),
            description=description,
            start=now(),
            attachments=[],
            labels=labels_of(item),
            status=None,
            steps=[],
            id=str(uuid.uuid4())
        )  # for later resolution in AllureAgregatingListener.pytest_sessionfinish

        self.stack = [self.test]

        yield

        self.test = None
        self.stack = []
Example #8
0
    def pytest_runtest_protocol(self, __multicall__, item, nextitem):
        if not self.testsuite:
            module = parent_module(item)

            self.impl.start_suite(name='.'.join(mangle_testnames(module.nodeid.split("::"))),
                                  description=module.module.__doc__ or None)
            self.testsuite = 'Yes'

        name = '.'.join(mangle_testnames([x.name for x in parent_down_from_module(item)]))

        self.impl.start_case(name, description=item.function.__doc__, severity=severity_of(item))

        result = __multicall__.execute()

        if not nextitem or parent_module(item) != parent_module(nextitem):
            self.impl.stop_suite()
            self.testsuite = None

        return result
Example #9
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))
Example #10
0
    def pytest_collectreport(self, report):
        if not report.passed:
            if report.failed:
                status = Status.BROKEN
            else:
                status = Status.CANCELED

            self.fails.append(CollectFail(name=mangle_testnames(report.nodeid.split("::"))[-1],
                                          status=status,
                                          message=get_exception_message(None, None, report),
                                          trace=report.longrepr))
Example #11
0
    def pytest_collectreport(self, report):
        if not report.passed:
            if report.failed:
                status = Status.BROKEN
            else:
                status = Status.SKIPPED

            self.fails.append(CollectFail(name=mangle_testnames(report.nodeid.split("::"))[-1],
                                          status=status,
                                          message=get_exception_message(report),
                                          trace=report.longrepr))
Example #12
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)
Example #13
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,
    }
Example #14
0
    def pytest_runtest_protocol(self, item, nextitem):
        if not self.testsuite:
            module = parent_module(item)

            self.impl.start_suite(name=module.module.__name__,
                                  description=module.module.__doc__ or None)
            self.testsuite = 'Yes'

        name = '.'.join(mangle_testnames([x.name for x in parent_down_from_module(item)]))
        self.impl.start_case(name, description=item.function.__doc__, labels=labels_of(item))
        yield

        if not nextitem or parent_module(item) != parent_module(nextitem):
            self.impl.stop_suite()
            self.testsuite = None
Example #15
0
    def pytest_runtest_protocol(self, item, nextitem):
        self.test = TestCase(name='.'.join(mangle_testnames([x.name for x in parent_down_from_module(item)])),
                             description=item.function.__doc__,
                             start=now(),
                             attachments=[],
                             labels=labels_of(item),
                             status=None,
                             steps=[],
                             id=str(uuid.uuid4()))  # for later resolution in AllureAgregatingListener.pytest_sessionfinish

        self.stack = [self.test]

        yield

        self.test = None
        self.stack = []
Example #16
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)
                names = junitxml.mangle_testnames(request.node.nodeid.split("::"))
                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 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))
Example #17
0
    def pytest_runtest_protocol(self, item, nextitem):
        if not self.testsuite:
            module = parent_module(item)

            self.impl.start_suite(name=module.module.__name__,
                                  description=module.module.__doc__ or None)
            self.testsuite = 'Yes'

        name = '.'.join(
            mangle_testnames([x.name for x in parent_down_from_module(item)]))
        self.impl.start_case(name,
                             description=item.function.__doc__,
                             labels=labels_of(item))
        yield

        if not nextitem or parent_module(item) != parent_module(nextitem):
            self.impl.stop_suite()
            self.testsuite = None
Example #18
0
def browser_screenshot(request, splinter_screenshot_dir):
    """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)
                names = junitxml.mangle_testnames(
                    request.node.nodeid.split("::"))
                classname = '.'.join(names[:-1])
                screenshot_dir = os.path.join(splinter_screenshot_dir,
                                              classname)
                screenshot_file_name = '{0}-{1}.png'.format(
                    names[-1][:128 - len(name) - 5], name)
                if not slaveoutput:
                    if not os.path.exists(screenshot_dir):
                        os.makedirs(screenshot_dir)
                else:
                    screenshot_dir = session_tmpdir.mkdir(
                        'screenshots').strpath
                screenshot_path = os.path.join(screenshot_dir,
                                               screenshot_file_name)
                LOGGER.info('Saving screenshot to {0}'.format(screenshot_path))
                try:
                    browser.driver.save_screenshot(screenshot_path)
                    with open(screenshot_path) as fd:
                        if slaveoutput is not None:
                            slaveoutput.setdefault('screenshots', []).append({
                                'class_name':
                                classname,
                                'file_name':
                                screenshot_file_name,
                                'content':
                                fd.read()
                            })
                except Exception as e:
                    request.config.warn(
                        'SPL504', "Could not save screenshot: {0}".format(e))
Example #19
0
    def pytest_runtest_protocol(self, item, nextitem):
        try:
            # for common items
            description = item.function.__doc__
        except AttributeError:
            # for doctests that has no `function` attribute
            description = item.reportinfo()[2]
        self.test = TestCase(name='.'.join(mangle_testnames([x.name for x in parent_down_from_module(item)])),
                             description=description,
                             start=now(),
                             attachments=[],
                             labels=labels_of(item),
                             status=None,
                             steps=[],
                             id=str(uuid.uuid4()))  # for later resolution in AllureAgregatingListener.pytest_sessionfinish

        self.stack = [self.test]

        yield

        self.test = None
        self.stack = []
Example #20
0
def test_mangle_testnames():
    from _pytest.junitxml import mangle_testnames
    names = ["a/pything.py", "Class", "()", "method"]
    newnames = mangle_testnames(names)
    assert newnames == ["a.pything", "Class", "method"]
Example #21
0
def test_mangle_testnames():
    from _pytest.junitxml import mangle_testnames
    names = ["a/pything.py", "Class", "()", "method"]
    newnames = mangle_testnames(names)
    assert newnames == ["a.pything", "Class", "method"]