示例#1
0
 def test_setter_cannot_open_path(self):
     m = mock_open()
     m.side_effect = IOError("fail")
     gc = GlobalConfig()
     with patch("samcli.cli.global_config.open", m):
         with self.assertRaises(IOError):
             gc.telemetry_enabled = True
示例#2
0
 def test_setter_raises_on_invalid_json(self):
     path = Path(self._cfg_dir, "metadata.json")
     with open(str(path), "w") as f:
         f.write("NOT JSON, PROBABLY VALID YAML AM I RIGHT!?")
     gc = GlobalConfig(config_dir=self._cfg_dir)
     with self.assertRaises(ValueError):
         gc.telemetry_enabled = True
示例#3
0
 def test_set_telemetry_flag_no_key(self):
     path = Path(self._cfg_dir, "metadata.json")
     with open(str(path), "w") as f:
         cfg = {"installationId": "stub-uuid"}
         f.write(json.dumps(cfg, indent=4) + "\n")
     gc = GlobalConfig(config_dir=self._cfg_dir)
     gc.telemetry_enabled = True
     json_body = json.loads(path.read_text())
     self.assertTrue(gc.telemetry_enabled)
     self.assertTrue(json_body["telemetryEnabled"])
示例#4
0
 def test_set_telemetry_flag_no_file(self):
     path = Path(self._cfg_dir, "metadata.json")
     gc = GlobalConfig(config_dir=self._cfg_dir)
     self.assertFalse(gc.telemetry_enabled)  # pre-state test
     gc.telemetry_enabled = True
     from_gc = gc.telemetry_enabled
     json_body = json.loads(path.read_text())
     from_file = json_body["telemetryEnabled"]
     self.assertTrue(from_gc)
     self.assertTrue(from_file)
示例#5
0
 def test_set_telemetry_flag_overwrite(self):
     path = Path(self._cfg_dir, "metadata.json")
     with open(str(path), "w") as f:
         cfg = {"telemetryEnabled": True}
         f.write(json.dumps(cfg, indent=4) + "\n")
     gc = GlobalConfig(config_dir=self._cfg_dir)
     self.assertTrue(gc.telemetry_enabled)
     gc.telemetry_enabled = False
     json_body = json.loads(path.read_text())
     self.assertFalse(gc.telemetry_enabled)
     self.assertFalse(json_body["telemetryEnabled"])
示例#6
0
    def test_last_version_check_value_no_key(self):
        path = Path(self._cfg_dir, "metadata.json")
        with open(str(path), "w") as f:
            cfg = {"installationId": "stub-uuid"}
            f.write(json.dumps(cfg, indent=4) + "\n")
        gc = GlobalConfig(config_dir=self._cfg_dir)

        last_version_check_value = time()
        gc.last_version_check = last_version_check_value
        json_body = json.loads(path.read_text())
        self.assertEqual(gc.last_version_check, json_body["lastVersionCheck"])
示例#7
0
 def test_setter_cannot_open_file(self):
     path = Path(self._cfg_dir, "metadata.json")
     with open(str(path), "w") as f:
         cfg = {"telemetryEnabled": True}
         f.write(json.dumps(cfg, indent=4) + "\n")
     m = mock_open()
     m.side_effect = IOError("fail")
     gc = GlobalConfig(config_dir=self._cfg_dir)
     with patch("samcli.cli.global_config.open", m):
         with self.assertRaises(IOError):
             gc.telemetry_enabled = True
示例#8
0
    def test_set_last_version_check_value_no_file(self):
        path = Path(self._cfg_dir, "metadata.json")
        gc = GlobalConfig(config_dir=self._cfg_dir)
        self.assertIsNone(gc.last_version_check)  # pre-state test

        last_version_check_value = time()
        gc.last_version_check = last_version_check_value
        from_gc = gc.last_version_check
        json_body = json.loads(path.read_text())
        from_file = json_body["lastVersionCheck"]
        self.assertEqual(from_gc, from_file)
示例#9
0
    def test_set_last_version_check_value_overwrite(self):
        last_version_check_value = time()
        path = Path(self._cfg_dir, "metadata.json")
        with open(str(path), "w") as f:
            cfg = {"lastVersionCheck": last_version_check_value}
            f.write(json.dumps(cfg, indent=4) + "\n")

        gc = GlobalConfig(config_dir=self._cfg_dir)
        self.assertEqual(gc.last_version_check, last_version_check_value)

        last_version_check_new_value = time()
        gc.last_version_check = last_version_check_new_value
        json_body = json.loads(path.read_text())
        self.assertEqual(gc.last_version_check, json_body["lastVersionCheck"])
示例#10
0
def _inform_newer_version(force_check=False) -> None:
    """
    Compares installed SAM CLI version with the up to date version from PyPi,
    and print information if up to date version is different then what is installed now

    It will store last version check time into GlobalConfig, so that it won't be running all the time
    Currently, it will be checking weekly

    Parameters
    ----------
    check_all_always: bool
        When it is True, it will trigger checking new version of SAM CLI. Default value is False

    """
    # run everything else in try-except block
    global_config = None
    need_to_update_last_check_time = True
    try:
        global_config = GlobalConfig()
        last_version_check = global_config.last_version_check

        if force_check or is_version_check_overdue(last_version_check):
            fetch_and_compare_versions()
        else:
            need_to_update_last_check_time = False
    except Exception as e:
        LOG.debug("New version check failed", exc_info=e)
    finally:
        if need_to_update_last_check_time:
            update_last_check_time(global_config)
示例#11
0
 def test_last_version_check_value_not_in_cfg(self):
     path = Path(self._cfg_dir, "metadata.json")
     with open(str(path), "w") as f:
         cfg = {"installationId": "stub-uuid"}
         f.write(json.dumps(cfg, indent=4) + "\n")
     gc = GlobalConfig(config_dir=self._cfg_dir)
     self.assertIsNone(gc.last_version_check)
示例#12
0
 def test_telemetry_flag_explicit_false(self):
     path = Path(self._cfg_dir, "metadata.json")
     with open(str(path), 'w') as f:
         cfg = {"telemetryEnabled": True}
         f.write(json.dumps(cfg, indent=4) + "\n")
     gc = GlobalConfig(config_dir=self._cfg_dir, telemetry_enabled=False)
     self.assertFalse(gc.telemetry_enabled)
示例#13
0
 def test_telemetry_flag_from_cfg(self):
     path = Path(self._cfg_dir, "metadata.json")
     with open(str(path), "w") as f:
         cfg = {"telemetryEnabled": True}
         f.write(json.dumps(cfg, indent=4) + "\n")
     gc = GlobalConfig(config_dir=self._cfg_dir)
     self.assertTrue(gc.telemetry_enabled)
示例#14
0
 def test_invalid_json(self):
     path = Path(self._cfg_dir, "metadata.json")
     with open(str(path), "w") as f:
         f.write("NOT JSON, PROBABLY VALID YAML AM I RIGHT!?")
     gc = GlobalConfig(config_dir=self._cfg_dir)
     self.assertIsNone(gc.installation_id)
     self.assertFalse(gc.telemetry_enabled)
示例#15
0
 def test_telemetry_flag_not_in_cfg(self):
     path = Path(self._cfg_dir, "metadata.json")
     with open(str(path), "w") as f:
         cfg = {"installationId": "stub-uuid"}
         f.write(json.dumps(cfg, indent=4) + "\n")
     gc = GlobalConfig(config_dir=self._cfg_dir)
     self.assertFalse(gc.telemetry_enabled)
示例#16
0
 def test_config_write_error(self):
     m = mock_open()
     m.side_effect = IOError("fail")
     gc = GlobalConfig()
     with patch("samcli.cli.global_config.open", m):
         installation_id = gc.installation_id
         self.assertIsNone(installation_id)
示例#17
0
 def test_cli_prompt_false(self):
     gc = GlobalConfig(config_dir=self._cfg_dir)
     with mock.patch('samcli.cli.main.global_cfg', gc):
         self.assertIsNone(gc.telemetry_enabled)  # pre-state test
         runner = CliRunner()
         runner.invoke(cli, ["local", "generate-event", "s3"], input="Y")
         self.assertEqual(True, gc.telemetry_enabled)
示例#18
0
 def test_last_version_check_value_cfg(self):
     last_version_check_value = time()
     path = Path(self._cfg_dir, "metadata.json")
     with open(str(path), "w") as f:
         cfg = {"lastVersionCheck": last_version_check_value}
         f.write(json.dumps(cfg, indent=4) + "\n")
     gc = GlobalConfig(config_dir=self._cfg_dir)
     self.assertEqual(gc.last_version_check, last_version_check_value)
示例#19
0
 def test_cli_prompt(self):
     gc = GlobalConfig(config_dir=self._cfg_dir)
     with mock.patch('samcli.cli.main.global_cfg', gc):
         self.assertIsNone(gc.telemetry_enabled)  # pre-state test
         runner = CliRunner()
         runner.invoke(cli, ["local", "generate-event", "s3"])
         # assertFalse is not appropriate, because None would also count
         self.assertEqual(False, gc.telemetry_enabled)
示例#20
0
def get_boto_config_with_user_agent(**kwargs):
    gc = GlobalConfig()
    return Config(
        user_agent_extra=f"aws-sam-cli/{__version__}/{gc.installation_id}"
        if gc.telemetry_enabled
        else f"aws-sam-cli/{__version__}",
        **kwargs,
    )
示例#21
0
 def test_installation_id_exists(self):
     path = Path(self._cfg_dir, "metadata.json")
     with open(str(path), "w") as f:
         cfg = {"installationId": "stub-uuid"}
         f.write(json.dumps(cfg, indent=4) + "\n")
     gc = GlobalConfig(config_dir=self._cfg_dir)
     installation_id = gc.installation_id
     self.assertEqual("stub-uuid", installation_id)
示例#22
0
def send_installed_metric():
    LOG.debug("Sending Installed Metric")

    telemetry = Telemetry()
    metric = Metric("installed")
    metric.add_data("osPlatform", platform.system())
    metric.add_data("telemetryEnabled", bool(GlobalConfig().telemetry_enabled))
    telemetry.emit(metric, force_emit=True)
示例#23
0
    def test_update_last_check_time(self, mock_gc_get_value, mock_gc_set_value):
        mock_gc_get_value.return_value = None
        global_config = GlobalConfig()
        self.assertIsNone(global_config.last_version_check)

        update_last_check_time(global_config)
        self.assertIsNotNone(global_config.last_version_check)

        mock_gc_set_value.assert_has_calls([call("lastVersionCheck", ANY)])
示例#24
0
 def __init__(self, metric_name, should_add_common_attributes=True):
     self._data = dict()
     self._metric_name = metric_name
     self._gc = GlobalConfig()
     self._session_id = self._default_session_id()
     if not self._session_id:
         self._session_id = ""
     if should_add_common_attributes:
         self._add_common_metric_attributes()
示例#25
0
 def test_unable_to_create_dir(self):
     m = mock_open()
     m.side_effect = OSError("Permission DENIED")
     gc = GlobalConfig()
     with patch("samcli.cli.global_config.Path.mkdir", m):
         installation_id = gc.installation_id
         self.assertIsNone(installation_id)
         telemetry_enabled = gc.telemetry_enabled
         self.assertFalse(telemetry_enabled)
示例#26
0
 def test_missing_telemetry_flag(self, mock_os, mock_click, mock_path):
     gc = GlobalConfig()
     mock_click.get_app_dir.return_value = "mock/folders"
     path_mock = Mock()
     joinpath_mock = Mock()
     joinpath_mock.exists.return_value = False
     path_mock.joinpath.return_value = joinpath_mock
     mock_path.return_value = path_mock
     mock_os.environ = {}  # env var is not set
     self.assertIsNone(gc.telemetry_enabled)
示例#27
0
 def test_installation_id_on_existing_file(self):
     path = Path(self._cfg_dir, "metadata.json")
     with open(str(path), "w") as f:
         cfg = {"foo": "bar"}
         f.write(json.dumps(cfg, indent=4) + "\n")
     gc = GlobalConfig(config_dir=self._cfg_dir)
     installation_id = gc.installation_id
     json_body = json.loads(path.read_text())
     self.assertEqual(installation_id, json_body["installationId"])
     self.assertEqual("bar", json_body["foo"])
示例#28
0
 def test_installation_id_with_side_effect(self):
     gc = GlobalConfig(config_dir=self._cfg_dir)
     installation_id = gc.installation_id
     expected_path = Path(self._cfg_dir, "metadata.json")
     json_body = json.loads(expected_path.read_text())
     self.assertIsNotNone(installation_id)
     self.assertTrue(expected_path.exists())
     self.assertEqual(installation_id, json_body["installationId"])
     installation_id_refetch = gc.installation_id
     self.assertEqual(installation_id, installation_id_refetch)
示例#29
0
def _get_stack_template():
    gc = GlobalConfig()
    info = {
        "version": __version__,
        "installationId":
        gc.installation_id if gc.installation_id else "unknown"
    }

    template = """
    AWSTemplateFormatVersion : '2010-09-09'
    Transform: AWS::Serverless-2016-10-31
    Description: Managed Stack for AWS SAM CLI

    Metadata:
        SamCliInfo: {info}

    Resources:
      SamCliSourceBucket:
        Type: AWS::S3::Bucket
        Properties:
          VersioningConfiguration:
            Status: Enabled
          Tags:
            - Key: ManagedStackSource
              Value: AwsSamCli

      SamCliSourceBucketBucketPolicy:
        Type: AWS::S3::BucketPolicy
        Properties:
          Bucket: !Ref SamCliSourceBucket
          PolicyDocument:
            Statement:
              -
                Action:
                  - "s3:GetObject"
                Effect: "Allow"
                Resource:
                  Fn::Join:
                    - ""
                    -
                      - "arn:"
                      - !Ref AWS::Partition
                      - ":s3:::"
                      - !Ref SamCliSourceBucket
                      - "/*"
                Principal:
                  Service: serverlessrepo.amazonaws.com

    Outputs:
      SourceBucket:
        Value: !Ref SamCliSourceBucket
    """

    return template.format(info=json.dumps(info))
示例#30
0
 def test_setting_installation_id(self, mock_click, mock_path, mock_uuid):
     gc = GlobalConfig()
     mock_uuid.uuid4.return_value = "SevenLayerDipMock"
     path_mock = Mock()
     joinpath_mock = Mock()
     joinpath_mock.exists.return_value = False
     path_mock.joinpath.return_value = joinpath_mock
     mock_path.return_value = path_mock
     mock_click.get_app_dir.return_value = "mock/folders"
     mock_io = mock_open(Mock())
     with patch("samcli.cli.global_config.open", mock_io):
         self.assertEqual("SevenLayerDipMock", gc.installation_id)