def get_qml_viewer_app_path(self): try: qtversions = subprocess.check_output( ['qtchooser', '-list-versions'], universal_newlines=True).split('\n') check_func = self._find_qt_binary_chooser except OSError: # This means no qtchooser is installed, so let's check for # qmlviewer and qmlscene manually, the old way qtversions = ['qt4', 'qt5'] check_func = self._find_qt_binary_old not_found = True if 'qt4' in qtversions: path = check_func('qt4', 'qmlviewer') if path: not_found = False self.qml_viewer_app_path = path self.useFixture(EnvironmentVariable("QT_SELECT", "qt4")) if 'qt5' in qtversions: path = check_func('qt5', 'qmlscene') if path: not_found = False self.qml_viewer_app_path = path self.useFixture(EnvironmentVariable("QT_SELECT", "qt5")) if not_found: self.skip("Neither qmlviewer nor qmlscene is installed") return self.qml_viewer_app_path
def _setUp(self): code_dir = find_code_dir() unit_name = self._unit_name(code_dir) charm_dir = self._charm_dir(unit_name) self.config = self._default_config(code_dir) self._fs.add("/var") os.makedirs(charm_dir) self._create_symlink(code_dir, charm_dir, "metadata.yaml") self._create_symlink(code_dir, charm_dir, "templates") self.log = [] self.ports = {} self.unit_data = { "private-address": "10.1.2.3", "public-address": "", } self.useFixture(EnvironmentVariable("JUJU_UNIT_NAME", unit_name)) self.useFixture(EnvironmentVariable("CHARM_DIR", charm_dir)) self._processes.add(ConfigGet(self.config)) self._processes.add(JujuLog(self.log)) self._processes.add(OpenPort(self.ports)) self._processes.add(UnitGet(self.unit_data)) # If charmhelpers is around, clear its config cache. hookenv and hookenv.cache.clear()
def test_create_notifications(self): self.useFixture(EnvironmentVariable("SNAP", "/snap/maas/current")) snap_common_path = Path(self.make_dir()) self.useFixture( EnvironmentVariable("SNAP_COMMON", str(snap_common_path)) ) snap_common_path.joinpath("snap_mode").write_text("all", "utf-8") sync_deprecation_notifications() notification1, notification2 = Notification.objects.order_by("ident") self.assertEqual(notification1.ident, "deprecation_MD1_admins") self.assertEqual(notification1.category, "warning") self.assertFalse(notification1.dismissable) self.assertTrue(notification1.admins) self.assertFalse(notification1.users) self.assertIn( "https://maas.io/deprecations/MD1", notification1.message ) self.assertNotIn( "Please contact your MAAS administrator.", notification1.message ) self.assertEqual(notification2.ident, "deprecation_MD1_users") self.assertEqual(notification2.category, "warning") self.assertFalse(notification2.dismissable) self.assertFalse(notification2.admins) self.assertTrue(notification2.users) self.assertIn( "Please contact your MAAS administrator.", notification2.message )
def test_deprecation_notices_snap_not_all_mode(self): self.useFixture(EnvironmentVariable("SNAP", "/snap/maas/current")) snap_common_path = Path(self.make_dir()) self.useFixture( EnvironmentVariable("SNAP_COMMON", str(snap_common_path))) snap_common_path.joinpath("snap_mode").write_text( "region+rack", "utf-8") self.assertEqual(get_deprecations(), [])
def patch_dns_config_path(testcase, config_dir=None): """Set the DNS config dir to a temporary directory, and return its path.""" if config_dir is None: config_dir = testcase.make_dir() testcase.useFixture(EnvironmentVariable("MAAS_DNS_CONFIG_DIR", config_dir)) testcase.useFixture(EnvironmentVariable("MAAS_BIND_CONFIG_DIR", config_dir)) return config_dir
def test_deprecation_notices_snap_not_all_mode(self): self.useFixture(EnvironmentVariable("SNAP", "/snap/maas/current")) snap_common_path = Path(self.make_dir()) self.useFixture( EnvironmentVariable("SNAP_COMMON", str(snap_common_path))) snap_common_path.joinpath("snap_mode").write_text( "region+rack", "utf-8") handler = GeneralHandler(factory.make_User(), {}, None) self.assertEqual(handler.deprecation_notices({}), [])
def test_deprecation_notices_snap_all_mode(self): self.useFixture(EnvironmentVariable("SNAP", "/snap/maas/current")) snap_common_path = Path(self.make_dir()) self.useFixture( EnvironmentVariable("SNAP_COMMON", str(snap_common_path))) snap_common_path.joinpath("snap_mode").write_text("all", "utf-8") handler = GeneralHandler(factory.make_User(), {}, None) [notice] = handler.deprecation_notices({}) self.assertEqual(notice["id"], "MD1") self.assertEqual(notice["since"], "2.8")
def test_deprecation_notices_snap_all_mode(self): self.useFixture(EnvironmentVariable("SNAP", "/snap/maas/current")) snap_common_path = Path(self.make_dir()) self.useFixture( EnvironmentVariable("SNAP_COMMON", str(snap_common_path))) snap_common_path.joinpath("snap_mode").write_text("all", "utf-8") [notice] = get_deprecations() self.assertEqual(notice["id"], "MD1") self.assertEqual(notice["since"], "2.8") self.assertEqual(notice["url"], "https://maas.io/deprecations/MD1")
def _setup_environment(self): self.useFixture(EnvironmentVariable( 'ALTERNATIVE_CPIM_SERVICE_NAME', 'com.canonical.test.pim')) self.useFixture(EnvironmentVariable( 'FOLKS_BACKEND_PATH', os.path.join(get_service_library_path(), 'dummy.so'))) self.useFixture(EnvironmentVariable('FOLKS_BACKENDS_ALLOWED', 'dummy')) self.useFixture(EnvironmentVariable('FOLKS_PRIMARY_STORE', 'dummy')) self.useFixture(EnvironmentVariable( 'ADDRESS_BOOK_SERVICE_DEMO_DATA', self._get_vcard_location()))
def test_get_maas_cert_tuple_snap(self): certs_dir = self.tempdir / "certificates" certs_dir.mkdir(parents=True) (certs_dir / "maas.crt").touch() (certs_dir / "maas.key").touch() self.useFixture(EnvironmentVariable("SNAP_COMMON", str(self.tempdir))) self.useFixture(EnvironmentVariable("SNAP", "/snap/maas/current")) self.assertEqual( get_maas_cert_tuple(), ( f"{certs_dir}/maas.crt", f"{certs_dir}/maas.key", ), )
def test_get_maas_cert_tuple(self): certs_dir = self.tempdir / "etc/maas/certificates" certs_dir.mkdir(parents=True) (certs_dir / "maas.crt").touch() (certs_dir / "maas.key").touch() self.useFixture(EnvironmentVariable("MAAS_ROOT", str(self.tempdir))) self.useFixture(EnvironmentVariable("SNAP", None)) self.assertEqual( get_maas_cert_tuple(), ( f"{certs_dir}/maas.crt", f"{certs_dir}/maas.key", ), )
def _setUp(self): skel = Path(root).joinpath("run-skel") if skel.is_dir(): self.path = self.useFixture(TempDirectory()).join("run") # Work only in `run`; reference the old $MAAS_ROOT. etc = Path(self.path).joinpath("etc") # Create and populate $MAAS_ROOT/run/etc/{chrony,c/chrony.conf}. # The `.keep` file is not strictly necessary, but it's created for # consistency with the source tree's `run` directory. ntp = etc.joinpath("chrony") ntp.mkdir(parents=True) ntp.joinpath(".keep").touch() ntp_conf = ntp.joinpath("chrony.conf") ntp_conf.write_bytes( skel.joinpath("etc", "chrony", "chrony.conf").read_bytes()) # Create and populate $MAAS_ROOT/run/etc/maas. maas = etc.joinpath("maas") maas.mkdir(parents=True) maas.joinpath("drivers.yaml").symlink_to( skel.joinpath("etc", "maas", "drivers.yaml").resolve()) maas.joinpath("templates").mkdir() # Update the environment. self.useFixture(EnvironmentVariable("MAAS_ROOT", self.path)) else: raise NotADirectoryError( "Skeleton MAAS_ROOT (%s) is not a directory." % skel)
def setUp(self): if is_process_running(INDICATOR_NETWORK): _stop_process(INDICATOR_NETWORK) self.addCleanup(_start_process, INDICATOR_NETWORK) ctv_tmpl = os.path.join(os.path.dirname(__file__), 'connectivity.py') (self.ctv_mock, self.obj_ctv) = self.spawn_server_template( ctv_tmpl, parameters=self.connectivity_parameters, stdout=subprocess.PIPE) self.ctv_private = dbus.Interface( self.session_con.get_object(CTV_IFACE, CTV_PRIV_OBJ), 'org.freedesktop.DBus.Properties') self.ctv_nets = dbus.Interface( self.session_con.get_object(CTV_IFACE, CTV_NETS_OBJ), 'org.freedesktop.DBus.Properties') inetwork = os.path.join(os.path.dirname(__file__), 'indicatornetwork.py') (self.inetwork_mock, self.obj_inetwork) = self.spawn_server_template( inetwork, parameters=self.indicatornetwork_parameters, stdout=subprocess.PIPE) # Required since this test needs to dismiss the OSK. self.useFixture(EnvironmentVariable("UITK_USE_MALIIT", "1")) super(UbuntuSystemSettingsHotspotTestCase, self).setUp()
def test_defaults_to_process_environment(self): name = factory.make_name("name") value = factory.make_name("value") with EnvironmentVariable(name, value): self.assertThat( get_env_with_locale(), ContainsDict({name: Equals(value)}) )
def _write_snap_mode(self, mode): snap_common_path = Path(self.make_dir()) snap_mode_path = snap_common_path.joinpath("snap_mode") if mode is not None: snap_mode_path.write_text(mode, "utf-8") self.useFixture( EnvironmentVariable("SNAP_COMMON", str(snap_common_path)))
def test_get_bind_config_dir_checks_environ_first(self): directory = self.make_dir() self.useFixture(EnvironmentVariable("MAAS_BIND_CONFIG_DIR", directory)) self.assertThat( config.get_bind_config_dir(), MatchesAll(SamePath(directory), IsInstance(str)), )
def setUp(self): super(TestSudoGID, self).setUp() # Always ensure that SUDO_GID is not set in the environment. self.useFixture(EnvironmentVariable("SUDO_GID")) # We probably can't set EGID to anything we want in tests so we must # capture calls that attempt to do so. self.patch_autospec(utils, "setegid")
def setUp(self): super().setUp() # These steps need to happen in the right order otherwise they won't # get cleaned up properly and we'll be left in an incorrect timezone. self.addCleanup(time.tzset) self.useFixture(EnvironmentVariable('TZ', self._timezone)) time.tzset()
def test_get_dns_config_dir_defaults_to_etc_bind_maas(self): self.useFixture(EnvironmentVariable("MAAS_DNS_CONFIG_DIR")) self.assertThat( config.get_dns_config_dir(), MatchesAll(SamePath(locate_config("../bind/maas")), IsInstance(str)), )
def test_sets_and_resets_egid(self): original_egid = os.getegid() example_egid = original_egid + random.randrange(500, 1000) self.useFixture(EnvironmentVariable("SUDO_GID", str(example_egid))) with utils.sudo_gid(): self.assertThat(utils.setegid, MockCalledOnceWith(example_egid)) self.assertThat(utils.setegid, MockCalledWith(original_egid))
def setUp(self): super(DisplayFixture, self).setUp() self.process = Popen(self.command, stdin=PIPE, stdout=PIPE) self.display = self.process.stdout.readline().decode("ascii").strip() if not self.display or self.process.poll() is not None: raise CalledProcessError(self.process.returncode, self.command) self.useFixture(EnvironmentVariable("DISPLAY", self.display)) self.addCleanup(self.shutdown)
def test_log_deprecations(self): self.useFixture(EnvironmentVariable("SNAP", "/snap/maas/current")) snap_common_path = Path(self.make_dir()) self.useFixture( EnvironmentVariable("SNAP_COMMON", str(snap_common_path))) snap_common_path.joinpath("snap_mode").write_text("all", "utf-8") events = [] logger = LegacyLogger(observer=events.append) log_deprecations(logger=logger) [event] = events self.assertEqual( event["_message_0"], "Deprecation MD1 (https://maas.io/deprecations/MD1): " "MAAS is currently running the PostgreSQL database inside the snap. " "It should be migrated outside of the snap.", )
def test_output_error(self): self.useFixture(EnvironmentVariable('TESTR_PDB')) try: raise Exception('fooo') except Exception: err_tuple = sys.exc_info() ui = self.get_test_ui() ui.output_error(err_tuple)
def test_sets_and_resets_egid_on_crash(self): original_egid = os.getegid() example_egid = original_egid + random.randrange(500, 1000) self.useFixture(EnvironmentVariable("SUDO_GID", str(example_egid))) with ExpectedException(ZeroDivisionError): with utils.sudo_gid(): 0 / 0 # A very realistic example. self.assertThat(utils.setegid, MockCalledWith(original_egid))
def test_present_executable(self): temp_dir = self.makeTemporaryDirectory() bin_dir = os.path.join(temp_dir, "bin") program = os.path.join(bin_dir, "program") write_file(program, "") os.chmod(program, 0o755) self.useFixture(EnvironmentVariable("PATH", bin_dir)) self.assertTrue(find_on_path("program"))
def setUp(self): """Mock account service dbus, go to background page""" # mock ubuntu art directory using a local path art_dir = '%s/../background_images/' % (os.path.dirname( os.path.realpath(__file__))) user_obj = '/user/foo' self.user_props = { 'BackgroundFile': dbus.String('%slaunchpad.jpg' % art_dir, variant_level=1) } # start dbus system bus self.mock_server = self.spawn_server(ACCOUNTS_IFACE, ACCOUNTS_OBJ, ACCOUNTS_IFACE, system_bus=True, stdout=subprocess.PIPE) sleep(2) # create account proxy self.acc_proxy = dbus.Interface( self.dbus_con.get_object(ACCOUNTS_IFACE, ACCOUNTS_OBJ), dbusmock.MOCK_IFACE) # let accountservice find a user object path self.acc_proxy.AddMethod(ACCOUNTS_IFACE, 'FindUserById', 'x', 'o', 'ret = "%s"' % user_obj) # add getter and setter to mock self.acc_proxy.AddMethods( 'org.freedesktop.DBus.Properties', [('Get', 's', 'v', 'ret = self.user_props[args[0]]'), ('Set', 'sv', '', 'self.user_props[args[0]] = args[1]')]) # add user object to mock self.acc_proxy.AddObject( user_obj, ACCOUNTS_USER_IFACE, self.user_props, [('SetBackgroundFile', 'v', '', 'self.Set("%s", "BackgroundFile", args[0]);' % ACCOUNTS_USER_IFACE), ('GetBackgroundFile', '', 'v', 'ret = self.Get("%s", "BackgroundFile")' % ACCOUNTS_USER_IFACE)]) # create user proxy self.user_proxy = dbus.Interface( self.dbus_con.get_object(ACCOUNTS_IFACE, user_obj), ACCOUNTS_USER_IFACE) # patch env variable self.useFixture( EnvironmentVariable('SYSTEM_SETTINGS_UBUNTU_ART_DIR', art_dir)) super(BackgroundBaseTestCase, self).setUp('background') self.assertThat(self.main_view.background_page.active, Eventually(Equals(True)))
def test_log_deprecations(self): self.useFixture(EnvironmentVariable("SNAP", "/snap/maas/current")) snap_common_path = Path(self.make_dir()) self.useFixture( EnvironmentVariable("SNAP_COMMON", str(snap_common_path)) ) snap_common_path.joinpath("snap_mode").write_text("all", "utf-8") events = [] logger = LegacyLogger(observer=events.append) log_deprecations(logger=logger) [event] = events self.assertEqual( event["_message_0"], "Deprecation MD1 (https://maas.io/deprecations/MD1): " "The setup for this MAAS is deprecated and not suitable for production " "environments, as the database is running inside the snap.", )
def makeFile(self, extra_content_length=None): extra_content_length_str = (str(extra_content_length) if extra_content_length is not None else None) self.useFixture( EnvironmentVariable("LP_EXTRA_CONTENT_LENGTH", extra_content_length_str)) port = self.useFixture(FakeServerTestSetup()).port url = "http://localhost:%d/" % port return _File(urlopen(url), url)
def test_removes_https_proxy_from_environment(self): https_proxy = factory.make_name("https-proxy") initial = EnvironmentVariable("https_proxy", https_proxy) self.useFixture(initial) # On entry, https_proxy is removed from the environment. with ProxiesDisabledFixture(): self.assertNotIn("https_proxy", os.environ) # On exit, http_proxy is restored. self.assertEqual(https_proxy, os.environ.get("https_proxy"))
def test__defaults_to_process_environment(self): name = factory.make_name("name") value = factory.make_name("value") with EnvironmentVariable(name, value): self.assertThat( get_env_with_bytes_locale(), ContainsDict({ name.encode("ascii"): Equals(value.encode("ascii")), }), )