예제 #1
0
    def test_configure_must_support_no_tty(self):
        self.fake_terminal = fixture_setup.FakeTerminal(isatty=False)
        self.useFixture(self.fake_terminal)
        logger_name = self.id()
        log.configure(logger_name, log_level=logging.DEBUG)
        logger = logging.getLogger(logger_name)

        logger.debug("Test debug")
        logger.info("Test info")
        logger.warning("Test warning")
        logger.error("Test error")
        logger.critical("Test critical")

        stdout = self.fake_terminal.getvalue()
        self.assertThat(stdout, Contains("Test debug"))
        self.assertThat(stdout, Contains("Test info"))
        self.assertThat(stdout, Not(Contains(self.info_color)))

        stderr = self.fake_terminal.getvalue(stderr=True)
        self.assertThat(stderr, Contains("Test warning"))
        self.assertThat(stderr, Not(Contains(self.warning_color)))
        self.assertThat(stderr, Not(Contains("\033[0m")))
        self.assertThat(stderr, Contains("Test error"))
        self.assertThat(stderr, Not(Contains(self.error_color)))
        self.assertThat(stderr, Contains("Test critical"))
        self.assertThat(stderr, Not(Contains(self.critical_color)))
예제 #2
0
    def setUp(self):
        super().setUp()
        temp_cwd_fixture = fixture_setup.TempCWD()
        self.useFixture(temp_cwd_fixture)
        self.path = temp_cwd_fixture.path

        # Use a separate path for XDG dirs, or changes there may be detected as
        # source changes.
        self.xdg_path = self.useFixture(fixtures.TempDir()).path
        self.useFixture(fixture_setup.TempXDG(self.xdg_path))
        self.fake_terminal = fixture_setup.FakeTerminal()
        self.useFixture(self.fake_terminal)
        self.useFixture(fixture_setup.SilentSnapProgress())
        # Some tests will directly or indirectly change the plugindir, which
        # is a module variable. Make sure that it is returned to the original
        # value when a test ends.
        self.addCleanup(common.set_plugindir, common.get_plugindir())
        self.addCleanup(common.set_schemadir, common.get_schemadir())
        self.addCleanup(common.set_librariesdir, common.get_librariesdir())
        self.addCleanup(common.reset_env)
        common.set_schemadir(os.path.join(get_snapcraft_path(), "schema"))
        self.fake_logger = fixtures.FakeLogger(level=logging.ERROR)
        self.useFixture(self.fake_logger)

        patcher = mock.patch("multiprocessing.cpu_count")
        self.cpu_count = patcher.start()
        self.cpu_count.return_value = 2
        self.addCleanup(patcher.stop)

        patcher = mock.patch(
            "snapcraft.internal.indicators.ProgressBar", new=SilentProgressBar
        )
        patcher.start()
        self.addCleanup(patcher.stop)

        # These are what we expect by default
        self.snap_dir = os.path.join(os.getcwd(), "snap")
        self.prime_dir = os.path.join(os.getcwd(), "prime")
        self.stage_dir = os.path.join(os.getcwd(), "stage")
        self.parts_dir = os.path.join(os.getcwd(), "parts")
        self.local_plugins_dir = os.path.join(self.snap_dir, "plugins")

        # Avoid installing patchelf in the tests
        self.useFixture(fixtures.EnvironmentVariable("SNAPCRAFT_NO_PATCHELF", "1"))

        # Disable Sentry reporting for tests, otherwise they'll hang waiting
        # for input
        self.useFixture(
            fixtures.EnvironmentVariable("SNAPCRAFT_ENABLE_SENTRY", "false")
        )

        machine = os.environ.get("SNAPCRAFT_TEST_MOCK_MACHINE", None)
        self.base_environment = fixture_setup.FakeBaseEnvironment(machine=machine)
        self.useFixture(self.base_environment)

        # Make sure "SNAPCRAFT_ENABLE_DEVELOPER_DEBUG" is reset between tests
        self.useFixture(
            fixtures.EnvironmentVariable("SNAPCRAFT_ENABLE_DEVELOPER_DEBUG")
        )
        self.useFixture(fixture_setup.FakeSnapcraftctl())
예제 #3
0
    def test_list_plugins_non_tty(self):
        self.maxDiff = None
        fake_terminal = fixture_setup.FakeTerminal(isatty=False)
        self.useFixture(fake_terminal)

        result = self.run_command([self.command_name])

        self.assertThat(result.exit_code, Equals(0))
        self.assertThat(result.output, Contains(self.default_plugin_output))
예제 #4
0
    def test_list_plugins_large_terminal(self):
        self.maxDiff = None
        fake_terminal = fixture_setup.FakeTerminal(columns=999)
        self.useFixture(fake_terminal)

        result = self.run_command([self.command_name])

        self.assertThat(result.exit_code, Equals(0))
        self.assertThat(result.output, Equals(self.default_plugin_output))
예제 #5
0
    def test_list_plugins_large_terminal(self):
        fake_terminal = fixture_setup.FakeTerminal(columns=999)
        self.useFixture(fake_terminal)

        result = self.run_command([self.command_name, "--base", "core18"])

        self.assertThat(result.exit_code, Equals(0))
        self.assertThat(result.output, Contains(self.default_plugin_output))
        self.fake_iter_modules.mock.assert_called_once_with(
            snapcraft.plugins.v1.__path__)
예제 #6
0
    def setUp(self):
        super().setUp()
        temp_cwd_fixture = fixture_setup.TempCWD()
        self.useFixture(temp_cwd_fixture)
        self.path = temp_cwd_fixture.path
        self.useFixture(fixture_setup.TempXDG(self.path))
        self.fake_terminal = fixture_setup.FakeTerminal()
        self.useFixture(self.fake_terminal)
        self.useFixture(fixture_setup.SilentSnapProgress())
        # Some tests will directly or indirectly change the plugindir, which
        # is a module variable. Make sure that it is returned to the original
        # value when a test ends.
        self.addCleanup(common.set_plugindir, common.get_plugindir())
        self.addCleanup(common.set_schemadir, common.get_schemadir())
        self.addCleanup(common.set_librariesdir, common.get_librariesdir())
        self.addCleanup(common.reset_env)
        common.set_schemadir(os.path.join(get_snapcraft_path(), 'schema'))
        self.fake_logger = fixtures.FakeLogger(level=logging.ERROR)
        self.useFixture(self.fake_logger)

        patcher = mock.patch('multiprocessing.cpu_count')
        self.cpu_count = patcher.start()
        self.cpu_count.return_value = 2
        self.addCleanup(patcher.stop)

        patcher = mock.patch('snapcraft.internal.indicators.ProgressBar',
                             new=SilentProgressBar)
        patcher.start()
        self.addCleanup(patcher.stop)

        # These are what we expect by default
        self.snap_dir = os.path.join(os.getcwd(), 'snap')
        self.prime_dir = os.path.join(os.getcwd(), 'prime')
        self.stage_dir = os.path.join(os.getcwd(), 'stage')
        self.parts_dir = os.path.join(os.getcwd(), 'parts')
        self.local_plugins_dir = os.path.join(self.snap_dir, 'plugins')

        # Avoid installing patchelf in the tests
        self.useFixture(
            fixtures.EnvironmentVariable('SNAPCRAFT_NO_PATCHELF', '1'))

        # Disable Sentry reporting for tests, otherwise they'll hang waiting
        # for input
        self.useFixture(
            fixtures.EnvironmentVariable('SNAPCRAFT_ENABLE_SENTRY', 'false'))

        machine = os.environ.get('SNAPCRAFT_TEST_MOCK_MACHINE', None)
        self.base_environment = fixture_setup.FakeBaseEnvironment(
            machine=machine)
        self.useFixture(self.base_environment)

        # Make sure SNAPCRAFT_DEBUG is reset between tests
        self.useFixture(fixtures.EnvironmentVariable('SNAPCRAFT_DEBUG'))
        self.useFixture(fixture_setup.FakeSnapcraftctl())
예제 #7
0
    def test_search_on_non_tty(self):
        fake_terminal = fixture_setup.FakeTerminal(isatty=False)
        self.useFixture(fake_terminal)

        result = self.run_command(['search', 'curl'])

        self.assertThat(result.exit_code, Equals(0))
        self.assertThat(
            result.output,
            Contains(
                dedent("""\
            PART NAME  DESCRIPTION
            curl       test entry for curl""")))
예제 #8
0
    def setUp(self):
        super().setUp()

        patcher = mock.patch('snapcraft.internal.indicators.is_dumb_terminal')
        dumb_mock = patcher.start()
        dumb_mock.return_value = True
        self.addCleanup(patcher.stop)

        self.useFixture(fixture_setup.FakeTerminal())

        patcher = mock.patch('snapcraft.internal.lifecycle._packer.Popen',
                             new=mock.Mock(wraps=subprocess.Popen))
        self.popen_spy = patcher.start()
        self.addCleanup(patcher.stop)
예제 #9
0
    def setUp(self):
        super().setUp()
        self.useFixture(fixture_setup.FakeTerminal())
        self.fake_logger = fixtures.FakeLogger(level=logging.DEBUG)
        self.useFixture(self.fake_logger)

        self.workdir = self.useFixture(fixtures.TempDir()).path
        self.source_file = os.path.join(self.workdir, "source.snap")
        self.target_file = os.path.join(self.workdir, "target.snap")

        with open(self.source_file, "wb") as f:
            f.write(b"This is the source file.")
        with open(self.target_file, "wb") as f:
            f.write(b"This is the target file.")
예제 #10
0
    def setUp(self):
        super().setUp()
        self.useFixture(fixture_setup.FakeTerminal())
        self.fake_logger = fixtures.FakeLogger(level=logging.INFO)
        self.useFixture(self.fake_logger)

        self.delta_tool_path = '/usr/bin/xdelta3'
        self.workdir = self.useFixture(fixtures.TempDir()).path
        self.source_file = os.path.join(self.workdir, 'source.snap')
        self.target_file = os.path.join(self.workdir, 'target.snap')

        with open(self.source_file, 'wb') as f:
            f.write(b'This is the source file.')
        with open(self.target_file, 'wb') as f:
            f.write(b'This is the target file.')
예제 #11
0
    def test_revisions_by_arch(self, mock_account_api, mock_revisions):
        fake_terminal = fixture_setup.FakeTerminal()
        self.useFixture(fake_terminal)

        mock_revisions.return_value = [
            rev for rev in self.expected if rev['arch'] == 'amd64']

        result = self.run_command([self.command_name, 'snap-test',
                                   '--arch=amd64'])

        self.assertThat(result.exit_code, Equals(0))
        self.assertThat(result.output, Contains(dedent("""\
            Rev.    Uploaded              Arch    Version    Channels
            1       2016-09-27T18:38:43Z  amd64   2.0.2      stable*, edge""")))  # noqa
        mock_revisions.assert_called_once_with('snap-test', '16', 'amd64')
예제 #12
0
    def setUp(self):
        super().setUp()
        self.useFixture(fixture_setup.FakeTerminal())
        self.fake_logger = fixtures.FakeLogger(level=logging.DEBUG)
        self.useFixture(self.fake_logger)

        self.patch(file_utils, 'executable_exists', lambda a: True)

        self.workdir = self.useFixture(fixtures.TempDir()).path
        self.source_file = os.path.join(self.workdir, 'source.snap')
        self.target_file = os.path.join(self.workdir, 'target.snap')

        with open(self.source_file, 'wb') as f:
            f.write(b'This is the source file.')
        with open(self.target_file, 'wb') as f:
            f.write(b'This is the target file.')
예제 #13
0
    def test_list_plugins_small_terminal(self):
        self.maxDiff = None
        fake_terminal = fixture_setup.FakeTerminal(columns=60)
        self.useFixture(fake_terminal)

        expected_output = (
            'ament         dump     kernel             python2    \n'
            'ant           go       make               python3    \n'
            'autotools     godeps   maven              qmake      \n'
            'catkin        gradle   meson              ruby       \n'
            'catkin-tools  gulp     nil                rust       \n'
            'cmake         jdk      nodejs             scons      \n'
            'copy          jhbuild  plainbox-provider  tar-content\n'
            'dotnet        kbuild   python             waf        \n')

        result = self.run_command([self.command_name])

        self.assertThat(result.exit_code, Equals(0))
        self.assertThat(result.output, Equals(expected_output))
예제 #14
0
    def test_list_plugins_small_terminal(self):
        fake_terminal = fixture_setup.FakeTerminal(columns=60)
        self.useFixture(fake_terminal)

        expected_output = [
            "fake            checkbox-provider  dumper      macaroon",
            "not-real        snake              cradle      breaktools",
            "dotruby         oxide              jamesbuild  gmake",
            "godependencies  web                maker",
            "kernelz         hornet             none",
            "planton         fake-tools         pmake",
        ]

        result = self.run_command([self.command_name, "--base", "core18"])

        self.assertThat(result.exit_code, Equals(0))
        output_slice = [o.strip() for o in result.output.splitlines()][1:]
        self.assertThat(output_slice, Equals(expected_output))
        self.fake_iter_modules.mock.assert_called_once_with(
            snapcraft.plugins.v1.__path__)
예제 #15
0
    def setUp(self):
        super().setUp()
        self.useFixture(fixture_setup.FakeTerminal())
        self.fake_logger = fixtures.FakeLogger(level=logging.INFO)
        self.useFixture(self.fake_logger)

        self.delta_tool_path = "/usr/bin/xdelta3"
        self.workdir = self.useFixture(fixtures.TempDir()).path
        self.source_file = os.path.join(self.workdir, "source.snap")
        self.target_file = os.path.join(self.workdir, "target.snap")

        with open(self.source_file, "wb") as f:
            f.write(b"This is the source file.")
        with open(self.target_file, "wb") as f:
            f.write(b"This is the target file.")

        self.useFixture(
            fixtures.MockPatch(
                "snapcraft.file_utils.get_tool_path",
                side_effect=lambda x: os.path.join("/usr", "bin", x),
            ))
예제 #16
0
    def setUp(self):
        super().setUp()
        self.useFixture(fixture_setup.FakeTerminal())
        self.fake_logger = fixtures.FakeLogger(level=logging.DEBUG)
        self.useFixture(self.fake_logger)

        # patch the ProgressBar to avoid mess up the test output
        patcher = mock.patch(
            'tests.unit.test_deltas_xdelta3.ProgressBar',
            new=unit.SilentProgressBar)
        patcher.start()
        self.addCleanup(patcher.stop)

        self.workdir = self.useFixture(fixtures.TempDir()).path
        self.source_file = os.path.join(self.workdir, 'source.snap')
        self.target_file = os.path.join(self.workdir, 'target.snap')

        with open(self.source_file, 'wb') as f:
            f.write(b'This is the source file.')
        with open(self.target_file, 'wb') as f:
            f.write(b'This is the target file.')
예제 #17
0
    def test_snap_defaults_on_a_tty(self):
        fake_logger = fixtures.FakeLogger(level=logging.INFO)
        self.useFixture(fake_logger)
        self.useFixture(fixture_setup.FakeTerminal())

        self.make_snapcraft_yaml()

        result = self.run_command(['snap'])

        self.assertThat(result.exit_code, Equals(0))
        self.assertThat(result.output,
                        Contains('\nSnapped snap-test_1.0_amd64.snap\n'))

        self.popen_spy.assert_called_once_with([
            'mksquashfs', self.prime_dir, 'snap-test_1.0_amd64.snap',
            '-noappend', '-comp', 'xz', '-no-xattrs', '-no-fragments',
            '-all-root'
        ],
                                               stderr=subprocess.STDOUT,
                                               stdout=subprocess.PIPE)

        self.assertThat('snap-test_1.0_amd64.snap', FileExists())
예제 #18
0
    def setUp(self):
        super().setUp()
        temp_cwd_fixture = fixture_setup.TempCWD()
        self.useFixture(temp_cwd_fixture)
        self.path = temp_cwd_fixture.path

        # Use a separate path for XDG dirs, or changes there may be detected as
        # source changes.
        self.xdg_path = self.useFixture(fixtures.TempDir()).path
        self.useFixture(fixture_setup.TempXDG(self.xdg_path))
        self.fake_terminal = fixture_setup.FakeTerminal()
        self.useFixture(self.fake_terminal)
        # Some tests will directly or indirectly change the plugindir, which
        # is a module variable. Make sure that it is returned to the original
        # value when a test ends.
        self.addCleanup(common.set_plugindir, common.get_plugindir())
        self.addCleanup(common.set_schemadir, common.get_schemadir())
        self.addCleanup(common.set_extensionsdir, common.get_extensionsdir())
        self.addCleanup(common.set_keyringsdir, common.get_keyringsdir())
        self.addCleanup(common.reset_env)
        common.set_schemadir(os.path.join(get_snapcraft_path(), "schema"))
        self.fake_logger = fixtures.FakeLogger(level=logging.ERROR)
        self.useFixture(self.fake_logger)

        # Some tests will change the apt Dir::Etc::Trusted and
        # Dir::Etc::TrustedParts directories. Make sure they're properly reset.
        self.addCleanup(
            apt.apt_pkg.config.set,
            "Dir::Etc::Trusted",
            apt.apt_pkg.config.find_file("Dir::Etc::Trusted"),
        )
        self.addCleanup(
            apt.apt_pkg.config.set,
            "Dir::Etc::TrustedParts",
            apt.apt_pkg.config.find_file("Dir::Etc::TrustedParts"),
        )

        patcher = mock.patch("os.sched_getaffinity")
        self.cpu_count = patcher.start()
        self.cpu_count.return_value = {1, 2}
        self.addCleanup(patcher.stop)

        # We do not want the paths to affect every test we have.
        patcher = mock.patch(
            "snapcraft.file_utils.get_snap_tool_path", side_effect=lambda x: x
        )
        patcher.start()
        self.addCleanup(patcher.stop)

        patcher = mock.patch(
            "snapcraft.internal.indicators.ProgressBar", new=SilentProgressBar
        )
        patcher.start()
        self.addCleanup(patcher.stop)

        # These are what we expect by default
        self.snap_dir = os.path.join(os.getcwd(), "snap")
        self.prime_dir = os.path.join(os.getcwd(), "prime")
        self.stage_dir = os.path.join(os.getcwd(), "stage")
        self.parts_dir = os.path.join(os.getcwd(), "parts")
        self.local_plugins_dir = os.path.join(self.snap_dir, "plugins")

        # Use this host to run through the lifecycle tests
        self.useFixture(
            fixtures.EnvironmentVariable("SNAPCRAFT_BUILD_ENVIRONMENT", "host")
        )

        # Make sure snap installation does the right thing
        self.fake_snapd.installed_snaps = [
            dict(name="core16", channel="stable", revision="10"),
            dict(name="core18", channel="stable", revision="10"),
        ]
        self.fake_snapd.snaps_result = [
            dict(name="core16", channel="stable", revision="10"),
            dict(name="core18", channel="stable", revision="10"),
        ]
        self.fake_snapd.find_result = [
            dict(
                core16=dict(
                    channel="stable",
                    channels={"latest/stable": dict(confinement="strict")},
                )
            ),
            dict(
                core18=dict(
                    channel="stable",
                    channels={"latest/stable": dict(confinement="strict")},
                )
            ),
        ]
        self.fake_snapd.snap_details_func = None

        self.fake_snap_command = fixture_setup.FakeSnapCommand()
        self.useFixture(self.fake_snap_command)

        # Avoid installing patchelf in the tests
        self.useFixture(fixtures.EnvironmentVariable("SNAPCRAFT_NO_PATCHELF", "1"))

        # Disable Sentry reporting for tests, otherwise they'll hang waiting
        # for input
        self.useFixture(
            fixtures.EnvironmentVariable("SNAPCRAFT_ENABLE_ERROR_REPORTING", "false")
        )

        # Don't let the managed host variable leak into tests
        self.useFixture(fixtures.EnvironmentVariable("SNAPCRAFT_MANAGED_HOST"))

        machine = os.environ.get("SNAPCRAFT_TEST_MOCK_MACHINE", None)
        self.base_environment = fixture_setup.FakeBaseEnvironment(machine=machine)
        self.useFixture(self.base_environment)

        # Make sure "SNAPCRAFT_ENABLE_DEVELOPER_DEBUG" is reset between tests
        self.useFixture(
            fixtures.EnvironmentVariable("SNAPCRAFT_ENABLE_DEVELOPER_DEBUG")
        )
        self.useFixture(fixture_setup.FakeSnapcraftctl())

        # Don't let host SNAPCRAFT_BUILD_INFO variable leak into tests
        self.useFixture(fixtures.EnvironmentVariable("SNAPCRAFT_BUILD_INFO"))