Пример #1
0
 def setUpClass(cls):
     socket.setdefaulttimeout(60)
     if os.environ.get('WITH_SELENIUM', False):
         time.sleep(1)
         # Start a virtual display server for running the tests headless.
         if os.environ.get('SELENIUM_HEADLESS', False):
             cls.vdisplay = xvfbwrapper.Xvfb(width=1280, height=720)
             cls.vdisplay.start()
         cls.selenium = WebDriver()
     super(SeleniumTestCase, cls).setUpClass()
Пример #2
0
def main():
    logging.basicConfig(level=logging.INFO, format="%(message)s")

    aparse = argparse.ArgumentParser()
    aparse.add_argument("actions",
                        nargs="*",
                        choices=[
                            "avd", "install", "firstboot", "kill", "run",
                            "wait-for-boot-completed"
                        ])
    aparse.add_argument("--android-port",
                        default=5554,
                        type=int,
                        help="Port to run emulator on (default: 5554)")
    aparse.add_argument("--avd-name",
                        default="x86_64",
                        help="Name of AVD to create/use (default: x86_64)")
    aparse.add_argument("--no-window",
                        action="store_true",
                        help="Pass -no-window to emulator")
    aparse.add_argument("--sdcard",
                        default=500,
                        type=int,
                        help="SD card size in MB (default: 500)")
    aparse.add_argument("--snapshot",
                        default="never",
                        choices=["never", "always", "save", "load"],
                        help="Use snapshots for fast reset (default: never)")
    aparse.add_argument("--writable",
                        action="store_true",
                        help="Allow remount /system (default: False)")
    aparse.add_argument("--xvfb",
                        action="store_true",
                        help="Run emulator under XVFB")
    args = aparse.parse_args()

    if args.xvfb and {"firstboot", "run"} & set(args.actions):
        xvfb = xvfbwrapper.Xvfb(width=1280, height=1024)
    else:
        xvfb = None

    try:
        if xvfb is not None:
            xvfb.start()

        ah = AndroidHelper(args.android_port, args.avd_name, args.no_window,
                           args.sdcard, args.snapshot, args.writable)
        for action in args.actions:
            getattr(ah, action.replace("-", "_"))()
    finally:
        if xvfb is not None:
            xvfb.stop()
Пример #3
0
 def setUp(self):
     if os.environ.get('INTEGRATION_TESTS', False):
         # Start a virtual display server for running the tests headless.
         if os.environ.get('SELENIUM_HEADLESS', False):
             self.vdisplay = xvfbwrapper.Xvfb(width=1280, height=720)
             self.vdisplay.start()
         # Start the Selenium webdriver and setup configuration.
         self.driver = selenium.webdriver.Firefox()
         self.conf = config.get_config()
     else:
         msg = "The INTEGRATION_TESTS env variable is not set."
         raise self.skipException(msg)
     super(BaseTestCase, self).setUp()
    def setUp(self):
        """Reset all tables before testing."""

        if "SAUCE_USERNAME" in os.environ and "SAUCE_ACCESS_KEY" in os.environ:

            platform = {
                "browserName": "firefox",
                "platform": "Windows 10",
                "version": "46.0",
            }
            capabilities = {
                "tunnel-identifier": os.environ["TRAVIS_JOB_NUMBER"],
            }
            metadata = {
                "name":
                self.id(),
                "build":
                "#%s %s" % (
                    os.environ["TRAVIS_BUILD_NUMBER"],
                    os.environ["TRAVIS_BRANCH"],
                ),
                "tags": [
                    "py" + os.environ["TRAVIS_PYTHON_VERSION"],
                    "CI",
                ],
                "passed":
                False,
            }
            capabilities.update(platform)
            capabilities.update(metadata)

            url = "http://{username}:{access_key}@localhost:4445/wd/hub".format(
                username=os.environ["SAUCE_USERNAME"],
                access_key=os.environ["SAUCE_ACCESS_KEY"],
            )

            self.driver = webdriver.Remote(desired_capabilities=capabilities,
                                           command_executor=url)

        else:
            self.xvfb = xvfbwrapper.Xvfb()
            self.addCleanup(self.xvfb.stop)
            self.xvfb.start()

            self.driver = webdriver.Firefox(timeout=60)

        self.addCleanup(self.driver.quit)

        self.driver.root_uri = self.get_server_url()

        super(TestUI, self).setUp()
Пример #5
0
    def __init__(self,
                 use_profile=None,
                 use_valgrind=False,
                 use_xvfb=False,
                 use_gdb=False):
        self._abort_tokens = set(
        )  # tokens used to notify log scanner to kill the browser process
        self._last_bin_path = None
        self._launches = 0  # number of successful browser launches
        self._logs = PuppetLogger()
        self._platform = platform.system().lower()
        self._proc = None
        self._profile_template = use_profile  # profile that is used as a template
        self._returncode = 0  # return code of target process
        self._use_valgrind = use_valgrind
        self._use_gdb = use_gdb
        self._workers = list()  # collection of threads and processes
        self._xvfb = None
        self.profile = None  # path to profile
        self.reason = self.RC_CLOSED  # why the target process was terminated

        if use_valgrind:
            if not self._platform.startswith("linux"):
                raise EnvironmentError("Valgrind is only supported on Linux")
            try:
                with open(os.devnull, "w") as null_fp:
                    subprocess.call(["valgrind", "--version"],
                                    stdout=null_fp,
                                    stderr=null_fp)
            except OSError:
                raise EnvironmentError("Please install Valgrind")

        if use_gdb:
            if not self._platform.startswith("linux"):
                raise EnvironmentError("GDB is only supported on Linux")
            try:
                with open(os.devnull, "w") as null_fp:
                    subprocess.call(["gdb", "--version"],
                                    stdout=null_fp,
                                    stderr=null_fp)
            except OSError:
                raise EnvironmentError("Please install GDB")

        if use_xvfb:
            if not self._platform.startswith("linux"):
                raise EnvironmentError("Xvfb is only supported on Linux")
            try:
                self._xvfb = xvfbwrapper.Xvfb(width=1280, height=1024)
            except NameError:
                raise EnvironmentError("Please install xvfbwrapper")
            self._xvfb.start()
Пример #6
0
    def setUp(self):
        self._configure_log()

        if not os.environ.get('INTEGRATION_TESTS', False):
            msg = "The INTEGRATION_TESTS env variable is not set."
            raise self.skipException(msg)

        # Start a virtual display server for running the tests headless.
        if os.environ.get('SELENIUM_HEADLESS', False):
            self.vdisplay = xvfbwrapper.Xvfb(width=1920, height=1080)
            args = []

            # workaround for memory leak in Xvfb taken from:
            # http://blog.jeffterrace.com/2012/07/xvfb-memory-leak-workaround.html
            args.append("-noreset")

            # disables X access control
            args.append("-ac")

            if hasattr(self.vdisplay, 'extra_xvfb_args'):
                # xvfbwrapper 0.2.8 or newer
                self.vdisplay.extra_xvfb_args.extend(args)
            else:
                self.vdisplay.xvfb_cmd.extend(args)
            self.vdisplay.start()

            self.addCleanup(self.vdisplay.stop)

        # Increase the default Python socket timeout from nothing
        # to something that will cope with slow webdriver startup times.
        # This *just* affects the communication between this test process
        # and the webdriver.
        socket.setdefaulttimeout(60)
        # Start the Selenium webdriver and setup configuration.
        desired_capabilities = dict(webdriver.desired_capabilities)
        desired_capabilities['loggingPrefs'] = {'browser': 'ALL'}
        self.driver = webdriver.WebDriverWrapper(
            desired_capabilities=desired_capabilities)
        if self.CONFIG.selenium.maximize_browser:
            self.driver.maximize_window()
        self.driver.implicitly_wait(self.CONFIG.selenium.implicit_wait)
        self.driver.set_page_load_timeout(self.CONFIG.selenium.page_timeout)

        self.addCleanup(self.driver.quit)

        self.addOnException(self._attach_page_source)
        self.addOnException(self._attach_screenshot)
        self.addOnException(self._attach_browser_log)
        self.addOnException(self._attach_test_log)

        super(BaseTestCase, self).setUp()
Пример #7
0
 def setUp(self):
     if os.environ.get('INTEGRATION_TESTS', False):
         # Start a virtual display server for running the tests headless.
         if os.environ.get('SELENIUM_HEADLESS', False):
             self.vdisplay = xvfbwrapper.Xvfb(width=1280, height=720)
             self.vdisplay.start()
         # Start the Selenium webdriver and setup configuration.
         self.driver = webdriver.WebDriverWrapper()
         self.driver.maximize_window()
         self.conf = config.get_config()
         self.driver.implicitly_wait(self.conf.dashboard.page_timeout)
     else:
         msg = "The INTEGRATION_TESTS env variable is not set."
         raise self.skipException(msg)
     super(BaseTestCase, self).setUp()
def Declaranet(funcionarios_list, s3c, raw_bucket, bucket):

    initial_url = "http://servidorespublicos.gob.mx"

    now = datetime.datetime.now()

    try:
        driver.stop()

    except:
        pass

    # Web Driver setup
    display = xvfbwrapper.Xvfb()
    display.start()
    chromedriver = "/usr/lib/chromium-browser/chromium-browser"
    os.environ["webdriver.chrome.driver"] = chromedriver
    chromeOptions = webdriver.ChromeOptions()
    mime_types = "application/pdf,application/vnd.adobe.xfdf,application/vnd.fdf,application/vnd.adobe.xdp+xml"
    prefs = {
        "browser.download.folderList": 2,
        "browser.download.dir": u'/home/ubuntu',
        "browser.download.manager.showWhenStarting": False,
        "browser.helperApps.neverAsk.saveToDisk": mime_types,
        "pdfjs.disabled": "true",
        "plugins.plugins_list": [{
            "enabled": False,
            "name": "Chrome PDF Viewer"
        }],
        "plugin.disable_full_page_plugin_for_types": mime_types
    }
    chromeOptions.add_argument('--no-sandbox')
    chromeOptions.add_experimental_option("prefs", prefs)
    #driver = webdriver.Chrome(chrome_options=chromeOptions)
    driver = webdriver.Chrome("/usr/lib/chromium-browser/chromedriver",
                              chrome_options=chromeOptions)
    driver.implicitly_wait(50)
    driver.get(initial_url)

    link = None
    while not link:
        try:
            link = driver.find_element_by_class_name('ui-icon-closethick')
            link.click()
        except NoSuchElementException, e:
            print "Unable to click, retrying"
        else:
            break
Пример #9
0
def pytest_configure(config):
    """Start Xvfb if we're on Linux, not on a CI and Xvfb is available.

    This is a lot nicer than having windows popping up.
    """
    config.xvfb_display = None
    if sys.platform.startswith('linux') and not config.getoption('--no-xvfb'):
        assert 'QUTE_BUILDBOT' not in os.environ
        try:
            disp = xvfbwrapper.Xvfb(width=800, height=600, colordepth=16)
            disp.start()
        except FileNotFoundError:
            # We run without Xvfb if it's unavailable.
            pass
        else:
            config.xvfb_display = disp
Пример #10
0
def virtual_display(request):
    """Run test in virtual X server if env var is defined."""
    if request.config.option.disable_virtual_display:
        return

    _virtual_display = xvfbwrapper.Xvfb(*config.RESOLUTION)
    # workaround for memory leak in Xvfb taken from:
    # http://blog.jeffterrace.com/2012/07/xvfb-memory-leak-workaround.html
    # and disables X access control
    args = ["-noreset", "-ac"]

    _virtual_display.extra_xvfb_args.extend(args)

    with process_mutex.Lock(config.XVFB_LOCK):
        _virtual_display.start()

    request.addfinalizer(_virtual_display.stop)
Пример #11
0
 def __enter__(self):
     if self.disable_xvfb:
         return None
     self.display = xvfbwrapper.Xvfb(width=1280, height=1024)
     self.display.start()
     for i in self.display.xvfb_cmd:
         if i.startswith(':'):
             display_name = i
             break
     logger.info(
         'Starting the blackbox window manager in a virtual display.')
     try:
         self.blackbox = subprocess.Popen(['blackbox'],
                                          env={'DISPLAY': display_name})
     except OSError, e:
         if str(e) == '[Errno 2] No such file or directory':
             raise error.NotInstalledError('blackbox')
         raise
Пример #12
0
 def setUp(self):
     if os.environ.get('INTEGRATION_TESTS', False):
         # Start a virtual display server for running the tests headless.
         if os.environ.get('SELENIUM_HEADLESS', False):
             self.vdisplay = xvfbwrapper.Xvfb(width=1280, height=720)
             # workaround for memory leak in Xvfb taken from: http://blog.
             # jeffterrace.com/2012/07/xvfb-memory-leak-workaround.html
             self.vdisplay.xvfb_cmd.append("-noreset")
             # disables X access control
             self.vdisplay.xvfb_cmd.append("-ac")
             self.vdisplay.start()
         # Start the Selenium webdriver and setup configuration.
         self.driver = webdriver.WebDriverWrapper()
         self.driver.maximize_window()
         self.conf = config.get_config()
         self.driver.implicitly_wait(self.conf.selenium.implicit_wait)
         self.driver.set_page_load_timeout(self.conf.selenium.page_timeout)
     else:
         msg = "The INTEGRATION_TESTS env variable is not set."
         raise self.skipException(msg)
     super(BaseTestCase, self).setUp()
Пример #13
0
  def _start_internal(self):
    self._started = True
    # Signals
    for sig in (signal.SIGINT, signal.SIGQUIT, signal.SIGTERM):
      signal.signal(sig, self.stop)

    # Setup the browser & xvfb
    self.xvfb = xvfbwrapper.Xvfb(width=1024, height=768)
    self.xvfb.start()
    self.browser = webdriver.Chrome(executable_path=self._chromedriver_path)
    self._run_event.set()
    self._stop_event.clear()


    self._thread = threading.Thread(target=self._wrap_run)
    self._thread.start()
    try:
      while True:
        time.sleep(self._interval)
        self._run_event.set()
    except KeyboardInterrupt:
      print 'Saw CTRL-C, shutting down.'
      self.stop()
Пример #14
0
 def setup(self):
     self.xvfb = xvfbwrapper.Xvfb()
     self.xvfb.start()
     self.browser = splinter.Browser('firefox')
Пример #15
0
def core(args, application):
    from django.conf import settings

    # configure django
    warnings.filterwarnings(
        "error",
        r"DateTimeField received a naive datetime",
        RuntimeWarning,
        r"django\.db\.models\.fields",
    )
    if args["--persistent"]:
        create_dir = persistent_dir
        if args["--persistent-path"]:
            parent_path = args["--persistent-path"]
        else:
            parent_path = "data"
    else:
        create_dir = temp_dir
        parent_path = "/dev/shm"

    with create_dir("static", parent_path) as STATIC_ROOT:  # NOQA
        with create_dir("media", parent_path) as MEDIA_ROOT:  # NOQA
            args["MEDIA_ROOT"] = MEDIA_ROOT
            args["STATIC_ROOT"] = STATIC_ROOT
            if args["cms_check"]:
                args["--cms"] = True

            if args["<command>"]:
                from django.core.management import execute_from_command_line

                options = [
                    option for option in args["options"]
                    if (option != "--cms" and "--extra-settings" not in option
                        and not option.startswith("--persistent"))
                ]
                _make_settings(args, application, settings, STATIC_ROOT,
                               MEDIA_ROOT)
                execute_from_command_line(options)

            else:
                _make_settings(args, application, settings, STATIC_ROOT,
                               MEDIA_ROOT)
                # run
                if args["test"]:
                    if args["--runner"]:
                        runner = args["--runner"]
                    else:
                        runner = settings.TEST_RUNNER

                    # make "Address already in use" errors less likely, see Django
                    # docs for more details on this env variable.
                    os.environ.setdefault("DJANGO_LIVE_TEST_SERVER_ADDRESS",
                                          "localhost:8000-9000")
                    if args["--xvfb"]:  # pragma: no cover
                        import xvfbwrapper

                        context = xvfbwrapper.Xvfb(width=1280, height=720)
                    else:

                        @contextlib.contextmanager
                        def null_context():
                            yield

                        context = null_context()

                    with context:
                        num_failures = test(
                            args["<test-label>"],
                            application,
                            args["--failfast"],
                            runner,
                            args["--runner-options"],
                            args.get("--verbose", 1),
                        )
                        sys.exit(num_failures)
                elif args["server"]:
                    server(args["--bind"], args["--port"],
                           args.get("--migrate", True),
                           args.get("--verbose", 1))
                elif args["cms_check"]:
                    cms_check(args.get("--migrate", True))
                elif args["compilemessages"]:
                    compilemessages(application)
                elif args["makemessages"]:
                    makemessages(application, locale=args["--locale"])
                elif args["makemigrations"]:
                    makemigrations(
                        application,
                        merge=args["--merge"],
                        dry_run=args["--dry-run"],
                        empty=args["--empty"],
                        extra_applications=args["<extra-applications>"],
                    )
                elif args["pyflakes"]:
                    return static_analisys(application)
                elif args["authors"]:
                    return generate_authors()
                elif args["setup"]:
                    return setup_env(settings)
Пример #16
0
    def setUp(self):
        self._configure_log()

        self.addOnException(
            lambda exc_info: setattr(self, '_need_attach_test_log', True))

        def cleanup():
            if getattr(self, '_need_attach_test_log', None):
                self._attach_test_log()

        self.addCleanup(cleanup)

        width, height = SCREEN_SIZE
        display = '0.0'
        # Start a virtual display server for running the tests headless.
        if IS_SELENIUM_HEADLESS:
            width, height = 1920, 1080
            self.vdisplay = xvfbwrapper.Xvfb(width=width, height=height)
            args = []

            # workaround for memory leak in Xvfb taken from:
            # http://blog.jeffterrace.com/2012/07/xvfb-memory-leak-workaround.html
            args.append("-noreset")

            # disables X access control
            args.append("-ac")

            if hasattr(self.vdisplay, 'extra_xvfb_args'):
                # xvfbwrapper 0.2.8 or newer
                self.vdisplay.extra_xvfb_args.extend(args)
            else:
                self.vdisplay.xvfb_cmd.extend(args)
            self.vdisplay.start()
            display = self.vdisplay.new_display

            self.addCleanup(self.vdisplay.stop)

        self.video_recorder = VideoRecorder(width, height, display=display)
        self.video_recorder.start()

        self.addOnException(
            lambda exc_info: setattr(self, '_need_attach_video', True))

        def cleanup():
            self.video_recorder.stop()
            if getattr(self, '_need_attach_video', None):
                self._attach_video()
            else:
                self.video_recorder.clear()

        self.addCleanup(cleanup)

        # Increase the default Python socket timeout from nothing
        # to something that will cope with slow webdriver startup times.
        # This *just* affects the communication between this test process
        # and the webdriver.
        socket.setdefaulttimeout(60)
        # Start the Selenium webdriver and setup configuration.
        desired_capabilities = dict(webdriver.desired_capabilities)
        desired_capabilities['loggingPrefs'] = {'browser': 'ALL'}
        self.driver = webdriver.WebDriverWrapper(
            desired_capabilities=desired_capabilities)
        if self.CONFIG.selenium.maximize_browser:
            self.driver.maximize_window()
            if IS_SELENIUM_HEADLESS:  # force full screen in xvfb
                self.driver.set_window_size(width, height)

        self.driver.implicitly_wait(self.CONFIG.selenium.implicit_wait)
        self.driver.set_page_load_timeout(self.CONFIG.selenium.page_timeout)

        self.addOnException(self._attach_page_source)
        self.addOnException(self._attach_screenshot)
        self.addOnException(
            lambda exc_info: setattr(self, '_need_attach_browser_log', True))

        def cleanup():
            if getattr(self, '_need_attach_browser_log', None):
                self._attach_browser_log()
            self.driver.quit()

        self.addCleanup(cleanup)

        super(BaseTestCase, self).setUp()
Пример #17
0
 def setUp(self):
     self.display = xvfbwrapper.Xvfb(width=1280, height=720)
     self.display.start()
     self.driver = webdriver.PhantomJS()
Пример #18
0
def main():
    args = docopt(__doc__, version=cms.__version__)

    if args['pyflakes']:
        return static_analysis.pyflakes()

    if args['authors']:
        return generate_authors()

    # configure django
    warnings.filterwarnings('error',
                            r"DateTimeField received a naive datetime",
                            RuntimeWarning, r'django\.db\.models\.fields')

    default_name = ':memory:' if args['test'] else 'local.sqlite'

    db_url = os.environ.get("DATABASE_URL",
                            "sqlite://localhost/%s" % default_name)
    migrate = args.get('--migrate', False)

    with temp_dir() as STATIC_ROOT:
        with temp_dir() as MEDIA_ROOT:
            use_tz = VERSION[:2] >= (1, 4)

            configs = {
                'db_url': db_url,
                'ROOT_URLCONF': 'cms.test_utils.project.urls',
                'STATIC_ROOT': STATIC_ROOT,
                'MEDIA_ROOT': MEDIA_ROOT,
                'USE_TZ': use_tz,
                'SOUTH_TESTS_MIGRATE': migrate,
            }

            if args['test']:
                configs[
                    'SESSION_ENGINE'] = "django.contrib.sessions.backends.cache"

            # Command line option takes precedent over environment variable
            auth_user_model = args['--user']

            if not auth_user_model:
                auth_user_model = os.environ.get("AUTH_USER_MODEL", None)

            if auth_user_model:
                if VERSION[:2] < (1, 5):
                    print()
                    print(
                        "Custom user models are not supported before Django 1.5"
                    )
                    print()
                else:
                    configs['AUTH_USER_MODEL'] = auth_user_model

            configure(**configs)

            # run
            if args['test']:
                # make "Address already in use" errors less likely, see Django
                # docs for more details on this env variable.
                os.environ.setdefault('DJANGO_LIVE_TEST_SERVER_ADDRESS',
                                      'localhost:8000-9000')
                if args['--xvfb']:
                    import xvfbwrapper
                    context = xvfbwrapper.Xvfb(width=1280, height=720)
                else:

                    @contextlib.contextmanager
                    def null_context():
                        yield

                    context = null_context()

                with context:
                    if args['isolated']:
                        failures = isolated(args['<test-label>'],
                                            args['--parallel'])
                        print()
                        print("Failed tests")
                        print("============")
                        if failures:
                            for failure in failures:
                                print(" - %s" % failure)
                        else:
                            print(" None")
                        num_failures = len(failures)
                    elif args['timed']:
                        num_failures = timed(args['<test-label>'])
                    else:
                        num_failures = test(args['<test-label>'],
                                            args['--parallel'],
                                            args['--failfast'])
                    sys.exit(num_failures)
            elif args['server']:
                server(args['--bind'], args['--port'],
                       args.get('--migrate', True))
            elif args['shell']:
                shell()
            elif args['compilemessages']:
                compilemessages()
            elif args['makemessages']:
                makemessages()
            elif args['makemigrations']:
                makemigrations()
Пример #19
0
def init_test_environ():
    """This needs to be called before any test can be run.

    Before exiting the process call exit_test_environ() to clean up
    any resources created.
    """

    global _TEMP_DIR, _BUS_INFO, _VDISPLAY

    # create a user dir in /tmp and set env vars
    _TEMP_DIR = tempfile.mkdtemp(prefix=fsnative(u"QL-TEST-"))

    # needed for dbus/dconf
    runtime_dir = tempfile.mkdtemp(prefix=fsnative(u"RUNTIME-"), dir=_TEMP_DIR)
    os.chmod(runtime_dir, 0o700)
    environ["XDG_RUNTIME_DIR"] = runtime_dir

    # force the old cache dir so that GStreamer can re-use the GstRegistry
    # cache file
    environ["XDG_CACHE_HOME"] = xdg_get_cache_home()
    # GStreamer will update the cache if the environment has changed
    # (in Gst.init()). Since it takes 0.5s here and doesn't add much,
    # disable it. If the registry cache is missing it will be created
    # despite this setting.
    environ["GST_REGISTRY_UPDATE"] = fsnative(u"no")

    # set HOME and remove all XDG vars that default to it if not set
    home_dir = tempfile.mkdtemp(prefix=fsnative(u"HOME-"), dir=_TEMP_DIR)
    environ["HOME"] = home_dir

    # set to new default
    environ.pop("XDG_DATA_HOME", None)
    environ.pop("XDG_CONFIG_HOME", None)

    # don't use dconf
    environ["GSETTINGS_BACKEND"] = "memory"

    # don't use dconf
    environ["GSETTINGS_BACKEND"] = "memory"

    # Force the default theme so broken themes don't affect the tests
    environ["GTK_THEME"] = "Adwaita"

    if xvfbwrapper is not None:
        _VDISPLAY = xvfbwrapper.Xvfb()
        _VDISPLAY.start()

    _BUS_INFO = None
    if os.name != "nt" and sys.platform != "darwin":
        _BUS_INFO = dbus_launch_user()
        environ.update(_BUS_INFO)

    quodlibet.init(no_translations=True, no_excepthook=True)
    quodlibet.app.name = "QL Tests"

    # try to make things the same in case a different locale is active.
    # LANG for gettext, setlocale for number formatting etc.
    # Note: setlocale has to be called after Gtk.init()
    try:
        if os.name != "nt":
            environ["LANG"] = locale.setlocale(locale.LC_ALL, "en_US.UTF-8")
        else:
            environ["LANG"] = "en_US.utf8"
            locale.setlocale(locale.LC_ALL, "english")
    except locale.Error:
        pass
Пример #20
0
def core(args, application):
    from django.conf import settings

    # configure django
    warnings.filterwarnings('error',
                            r"DateTimeField received a naive datetime",
                            RuntimeWarning, r'django\.db\.models\.fields')

    with temp_dir() as STATIC_ROOT:
        with temp_dir() as MEDIA_ROOT:
            if args['cms_check']:
                args['--cms'] = True

            if args['<command>']:
                from django.core.management import execute_from_command_line
                options = [
                    option for option in args['options']
                    if (option != '--cms' and '--extra-settings' not in option)
                ]
                _make_settings(args, application, settings, STATIC_ROOT,
                               MEDIA_ROOT)
                execute_from_command_line(options)

            else:
                _make_settings(args, application, settings, STATIC_ROOT,
                               MEDIA_ROOT)
                # run
                if args['test']:
                    if args['--nose-runner']:
                        runner = 'django_nose.NoseTestSuiteRunner'
                    elif args['--simple-runner']:
                        runner = 'django.test.simple.DjangoTestSuiteRunner'
                    elif args['--runner']:
                        runner = args['--runner']
                    else:
                        runner = 'django.test.runner.DiscoverRunner'

                    # make "Address already in use" errors less likely, see Django
                    # docs for more details on this env variable.
                    os.environ.setdefault('DJANGO_LIVE_TEST_SERVER_ADDRESS',
                                          'localhost:8000-9000')
                    if args['--xvfb']:  # pragma: no cover
                        import xvfbwrapper

                        context = xvfbwrapper.Xvfb(width=1280, height=720)
                    else:

                        @contextlib.contextmanager
                        def null_context():
                            yield

                        context = null_context()

                    with context:
                        num_failures = test(args['<test-label>'], application,
                                            args['--failfast'], runner,
                                            args['--runner-options'])
                        sys.exit(num_failures)
                elif args['server']:
                    server(args['--bind'], args['--port'],
                           args.get('--migrate', True))
                elif args['cms_check']:
                    cms_check(args.get('--migrate', True))
                elif args['compilemessages']:
                    compilemessages(application)
                elif args['makemessages']:
                    makemessages(application)
                elif args['makemigrations']:
                    makemigrations(
                        application,
                        merge=args['--merge'],
                        dry_run=args['--dry-run'],
                        empty=args['--empty'],
                        extra_applications=args['<extra-applications>'])
                elif args['pyflakes']:
                    return static_analisys(application)
                elif args['authors']:
                    return generate_authors()
Пример #21
0
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
import xvfbwrapper

# Start headless display
display = xvfbwrapper.Xvfb()
display.start()
print('display started')

chrome_options = Options()
chrome_options.add_argument('--no-sandbox')
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get("http://www.google.com")
print(driver.title)
driver.quit()
display.stop()
print('display stopped')
Пример #22
0
import os
import sys
import unittest

from flask_testing import LiveServerTestCase
import pytest
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
import xvfbwrapper

from tests import TestCase


@unittest.skipUnless(
    ("SAUCE_USERNAME" in os.environ or xvfbwrapper.Xvfb().xvfb_exists()),
    "Xvfb not installed")
class IntegrationTestCase(TestCase, LiveServerTestCase):
    """Test class for UI integration/workflow testing"""
    def setUp(self):
        """Reset all tables before testing."""

        if "SAUCE_USERNAME" in os.environ:
            # Configure driver for Sauce Labs
            # Presumes tunnel setup by Sauce Connect
            # On TravisCI, Sauce Connect tunnel setup by Sauce Labs addon
            # https://docs.travis-ci.com/user/sauce-connect
            platform = {
                "browserName": "firefox",
                "platform": "Windows 10",
                "version": "60.0",
Пример #23
0
 def setUp(self):
     super(TestBasics, self).setUp()
     # Setup Selenium Driver
     self.display = xvfbwrapper.Xvfb(width=1280, height=720)
     self.display.start()
     self.driver = webdriver.PhantomJS()
Пример #24
0
    def setUp(self):
        """Reset all tables before testing."""

        if "SAUCE_USERNAME" in os.environ:
            # Configure driver for Sauce Labs
            # Presumes tunnel setup by Sauce Connect
            # On TravisCI, Sauce Connect tunnel setup by Sauce Labs addon
            # https://docs.travis-ci.com/user/sauce-connect
            platform = {
                "browserName": "firefox",
                "platform": "Windows 10",
                "version": "60.0",
            }
            capabilities = {
                "tunnel-identifier": os.environ["TRAVIS_JOB_NUMBER"],
                "extendedDebugging": "true",
            }
            metadata = {
                "name":
                self.id(),
                "build":
                "#%s %s" % (
                    os.environ["TRAVIS_BUILD_NUMBER"],
                    os.environ["TRAVIS_BRANCH"],
                ),
                "tags": [
                    "py" + os.environ["TRAVIS_PYTHON_VERSION"],
                    "CI",
                ],
                "passed":
                False,
            }
            capabilities.update(platform)
            capabilities.update(metadata)

            url = "http://{user}:{access_key}@localhost:4445/wd/hub".format(
                user=os.environ["SAUCE_USERNAME"],
                access_key=os.environ["SAUCE_ACCESS_KEY"],
            )

            self.driver = webdriver.Remote(desired_capabilities=capabilities,
                                           command_executor=url)

        else:
            if "DISPLAY" not in os.environ:
                # Non-graphical environment; use xvfb
                self.xvfb = xvfbwrapper.Xvfb()
                self.addCleanup(self.xvfb.stop)
                self.xvfb.start()
            self.driver = webdriver.Firefox(timeout=60)

        self.addCleanup(self.driver.quit)

        self.driver.root_uri = self.get_server_url()
        self.driver.implicitly_wait(30)
        self.verificationErrors = []
        # default explicit wait time; use with Expected Conditions as needed
        self.wait = WebDriverWait(self.driver, 60)
        self.accept_next_alert = True

        super(IntegrationTestCase, self).setUp()
Пример #25
0
def run_subprocess_and_capture(cmd,
                               stdin=None,
                               cwd=None,
                               env={},
                               rlimits=None,
                               realtime=None,
                               slug=None,
                               image="out.png"):
    """
    a helper to make a limited subprocess with GUI capture functionality

    `cmd`, `cwd`, and `env` are exactly as `subprocess.popen` expects.

    `stdin` is the data to write to the stdin of the subprocess.

    `rlimits` is a list of tuples, the arguments to pass to
    `resource.setrlimit` to set limits on the process.

    `realtime` is the number of seconds to limit the execution of the process.

    `slug` is a short identifier for use in log messages.

    `image` the filename of the image to save

    this function waits until the process has finished executing before
    returning.

    returns a tuple of three values: the exit status code of the process, and
    the stdout and stderr of the process, as strings.

    """

    TIMEOUT = 1

    with xvfbwrapper.Xvfb() as display:

        # Set the display variable
        display_num = display.new_display
        env["DISPLAY"] = ":{}".format(display_num)

        subproc = subprocess.Popen(
            cmd,
            cwd=cwd,
            env=env,
            preexec_fn=functools.partial(set_process_limits, rlimits or ()),
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
        )

        if slug:
            log.info("Executed jailed code %s in %s, with PID %s", slug, cwd,
                     subproc.pid)

        try:
            subproc.wait(TIMEOUT)
        except:
            # Capture the screen
            print("Capturing image")
            subprocess.call("DISPLAY=:{} import -window root {}".format(
                display_num, image),
                            shell=True)

            # Kill the child if it doesn't exit automatically
            subproc.kill()

    stdout = subproc.stdout.read()
    stderr = subproc.stderr.read()

    return subproc.returncode, stdout, stderr