Пример #1
0
    def InitLogging(self, logs_dir=None):
        """Initialize the logger for testing.

    Args:
      logs_dir: str, The root directory to write logs to.  If None, use the
        standard one.
    """
        log.Reset()
        log.AddFileLogging(logs_dir or self.logs_dir)
Пример #2
0
 def testEncodingStdOutUtf8(self):
     sys.stdout = mock.MagicMock()
     sys.stdout.encoding = 'UTF-8'
     log.Reset()
     attr = console_attr.GetConsoleAttr(reset=True)
     locale_encoding = locale.getpreferredencoding()
     if locale_encoding and 'cp1252' in locale_encoding:
         self.assertEqual(attr.GetEncoding(), 'ascii')
     else:
         self.assertEqual(attr.GetEncoding(), 'utf8')
 def __init__(self, capture_streams=True):
   self._records = []
   SessionDeterminer.Mock()
   if capture_streams:
     self._streams = (OutputStreamCapturer(sys.stdout),
                      OutputStreamCapturer(sys.stderr),)
     sys.stdout, sys.stderr = self._streams  # pylint: disable=unpacking-non-sequence
     log.Reset(*self._streams)
     self._stdin = InputStreamCapturer(sys.stdin)
     sys.stdin = self._stdin
     self._fileio = FileIoCapturer()
   else:
     self._streams = None
     self._stdin = None
     self._fileio = None
Пример #4
0
    def SetUp(self):
        self._prev_log_level = log.getLogger().getEffectiveLevel()
        self.__root_dir = file_utils.TemporaryDirectory()
        self.root_path = self.__root_dir.path
        self.temp_path = self.CreateTempDir()
        self.global_config_path = self.CreateTempDir('config')
        encoding.SetEncodedValue(os.environ,
                                 config.CLOUDSDK_CONFIG,
                                 self.global_config_path,
                                 encoding='utf-8')

        # MONKEYPATCH: We'd like to StartObjectPatch but Popen is patched elsewhere.
        subprocess.Popen = self.__Popen

        # Redirect home to a temp directory.
        self.home_path = self.CreateTempDir()
        self.StartEnvPatch({'HOME': self.home_path})
        self.mock_get_home_path = self.StartPatch(
            'googlecloudsdk.core.util.files.GetHomeDir',
            return_value=self.home_path)
        self.mock_expandvars = self.StartPatch('os.path.expandvars',
                                               autospec=True,
                                               return_value=self.home_path)
        self.addCleanup(self._CloseDirs)
        self.addCleanup(resources.REGISTRY.Clear)

        # Make sure there is nothing in the environment before the tests starts.
        self.__CleanProperties(setup=True)
        self.addCleanup(self.__CleanProperties)

        # Turn these off for tests.
        properties.VALUES.GetInvocationStack()[:] = [{}]
        # This is not a real property but behaves like one.
        os.environ.pop('CLOUDSDK_ACTIVE_CONFIG_NAME', None)
        # pylint:disable=protected-access
        named_configs.FLAG_OVERRIDE_STACK._stack[:] = []

        # Make sure certain things are restored between tests
        self.install_props = self._GetInstallPropsStats()
        self.addCleanup(self._VerifyInstallProps)

        properties.VALUES.core.interactive_ux_style.Set(
            properties.VALUES.core.InteractiveUXStyles.TESTING.name)

        # The mocking of stdout and stderr happen in the test_case module whenever
        # a test is using output capture.  We need to reset the logger here to pick
        # up those settings.
        log.Reset()
Пример #5
0
    def GetCLI(self, force_init=True):
        """Loads the test commands with a temporary logging directory.

    Args:
      force_init: bool, True to completely reset the logger, False to add a new
        handler.

    Returns:
      calliope.CLI, The CLI object.
    """
        log.Reset()
        loader = calliope.CLILoader(name='test',
                                    command_root_directory=os.path.join(
                                        self.calliope_test_home, 'sdk1'),
                                    logs_dir=self.logs_dir)
        loader.AddModule('sdk2', os.path.join(self.calliope_test_home, 'sdk2'))
        return loader.Generate()
Пример #6
0
 def __init__(self, capture_streams=True):
   self._records = []
   self._interactive_ux_style = (
       properties.VALUES.core.interactive_ux_style.Get())
   properties.VALUES.core.interactive_ux_style.Set(
       properties.VALUES.core.InteractiveUXStyles.TESTING.name)
   self._disable_color = properties.VALUES.core.disable_color.Get()
   properties.VALUES.core.disable_color.Set(True)
   if capture_streams:
     self._streams = (OutputStreamCapturer(sys.stdout),
                      OutputStreamCapturer(sys.stderr),)
     sys.stdout, sys.stderr = self._streams  # pylint: disable=unpacking-non-sequence
     log.Reset(*self._streams)
     self._stdin = InputStreamCapturer(sys.stdin)
     sys.stdin = self._stdin
     self._fileio = FileIoCapturer()
   else:
     self._streams = None
     self._stdin = None
     self._fileio = None
Пример #7
0
  def TearDown(self):
    # We need to reset the logger here because it depends on properties and
    # the config directory, so that needs to happen before we unmock that stuff.
    # We have to explicitly pass in the original stdout and stderr streams
    # because when this runs, test_case.WithOutputCapture, will not yet have
    # unmocked these streams.  If we don't then log.Reset here would restore
    # log.out to the mocked sys.stdout and leave it in that state for subsequent
    # tests. This could result in "write to closed stream" exceptions for
    # subsequent log.out writes.
    # pylint:disable=protected-access
    log.Reset(sys.__stdout__, sys.__stderr__)
    self.assertEqual(self._prev_log_level,
                     log.getLogger().getEffectiveLevel(),
                     'The test or the code that is tested has modified the '
                     'logger level/verbosity and did not restore it.')

    self.root_path = None
    self.temp_path = None
    self.global_config_path = None
    os.environ.pop(config.CLOUDSDK_CONFIG, None)
    subprocess.Popen = self._REAL_POPEN
Пример #8
0
 def TearDown(self):
     log.Reset()
Пример #9
0
 def SetUp(self):
     log.Reset()
     log.SetUserOutputEnabled(True)