def _populate_user_info_msg(msg: UserInfo) -> None: msg.installation_id = Installation.instance().installation_id msg.installation_id_v3 = Installation.instance().installation_id_v3 if Credentials.get_current().activation: msg.email = Credentials.get_current().activation.email else: msg.email = ""
def _enqueue_new_report_message(self): self._report.generate_new_id() msg = ForwardMsg() msg.new_report.report_id = self._report.report_id msg.new_report.name = self._report.name msg.new_report.script_path = self._report.script_path # git deploy params deploy_params = self.get_deploy_params() if deploy_params is not None: repo, branch, module = deploy_params msg.new_report.deploy_params.repository = repo msg.new_report.deploy_params.branch = branch msg.new_report.deploy_params.module = module # Immutable session data. We send this every time a new report is # started, to avoid having to track whether the client has already # received it. It does not change from run to run; it's up to the # to perform one-time initialization only once. imsg = msg.new_report.initialize imsg.config.sharing_enabled = config.get_option( "global.sharingMode") != "off" imsg.config.gather_usage_stats = config.get_option( "browser.gatherUsageStats") imsg.config.max_cached_message_age = config.get_option( "global.maxCachedMessageAge") imsg.config.mapbox_token = config.get_option("mapbox.token") imsg.config.allow_run_on_save = config.get_option( "server.allowRunOnSave") imsg.environment_info.streamlit_version = __version__ imsg.environment_info.python_version = ".".join( map(str, sys.version_info)) imsg.session_state.run_on_save = self._run_on_save imsg.session_state.report_is_running = ( self._state == ReportSessionState.REPORT_IS_RUNNING) imsg.user_info.installation_id = Installation.instance( ).installation_id imsg.user_info.installation_id_v1 = Installation.instance( ).installation_id_v1 imsg.user_info.installation_id_v2 = Installation.instance( ).installation_id_v2 imsg.user_info.installation_id_v3 = Installation.instance( ).installation_id_v3 if Credentials.get_current().activation: imsg.user_info.email = Credentials.get_current().activation.email else: imsg.user_info.email = "" imsg.command_line = self._report.command_line imsg.session_id = self.id self.enqueue(msg)
def test_Credentials_reset_error(self): """Test Credentials.reset() with error.""" with patch('streamlit.credentials.os.remove', side_effect=OSError('some error')), patch( 'streamlit.credentials.LOGGER') as p: Credentials.reset() p.error.assert_called_once_with( 'Error removing credentials file: some error')
def test_Credentials_reset(self): """Test Credentials.reset().""" c = Credentials.get_current() with patch("streamlit.credentials.os.remove") as p: Credentials.reset() p.assert_called_once_with("/mock/home/folder/.streamlit/credentials.toml") self.assertEqual(c, Credentials.get_current())
def test_Credentials_constructor_runs_twice(self): """Test Credentials constructor runs twice.""" Credentials._singleton = None Credentials() with pytest.raises(RuntimeError) as e: Credentials() self.assertEqual( str(e.value), "Credentials already initialized. Use .get_current() instead")
def _maybe_enqueue_initialize_message(self): if self._sent_initialize_message: return self._sent_initialize_message = True msg = ForwardMsg() imsg = msg.initialize imsg.config.sharing_enabled = config.get_option( "global.sharingMode") != "off" imsg.config.gather_usage_stats = config.get_option( "browser.gatherUsageStats") imsg.config.max_cached_message_age = config.get_option( "global.maxCachedMessageAge") imsg.config.mapbox_token = config.get_option("mapbox.token") imsg.config.allow_run_on_save = config.get_option( "server.allowRunOnSave") LOGGER.debug( "New browser connection: " "gather_usage_stats=%s, " "sharing_enabled=%s, " "max_cached_message_age=%s", imsg.config.gather_usage_stats, imsg.config.sharing_enabled, imsg.config.max_cached_message_age, ) imsg.environment_info.streamlit_version = __version__ imsg.environment_info.python_version = ".".join( map(str, sys.version_info)) imsg.session_state.run_on_save = self._run_on_save imsg.session_state.report_is_running = ( self._state == ReportSessionState.REPORT_IS_RUNNING) imsg.user_info.installation_id = Installation.instance( ).installation_id imsg.user_info.installation_id_v1 = Installation.instance( ).installation_id_v1 imsg.user_info.installation_id_v2 = Installation.instance( ).installation_id_v2 if Credentials.get_current().activation: imsg.user_info.email = Credentials.get_current().activation.email else: imsg.user_info.email = "" imsg.command_line = self._report.command_line imsg.session_id = self.id self.enqueue(msg)
def _main_run(file, args=[]): Credentials.get_current().check_activated(auto_resolve=True) import streamlit.bootstrap as bootstrap import sys # We don't use args ourselves. We just allow people to pass them so their # script can handle them via sys.argv or whatever. # IMPORTANT: This means we should treat argv carefully inside our code! sys.argv = [file] + list(args) bootstrap.run(file)
def _main_run(file, args=[]): command_line = _get_command_line_as_string() # Set a global flag indicating that we're "within" streamlit. streamlit._is_running_with_streamlit = True # Check credentials. Credentials.get_current().check_activated(auto_resolve=True) # Notify if streamlit is out of date. if version.should_show_new_version_notice(): click.echo(NEW_VERSION_TEXT) bootstrap.run(file, command_line, args)
def test_Credentials_check_activated_false(self): """Test Credentials.check_activated() not activated.""" c = Credentials.get_current() c.activation = Activation('some_email', 'some_code', False) with patch('streamlit.credentials._exit') as p: c.check_activated() p.assert_called_once_with('Activation code/email not valid.')
def test_Credentials_check_activated_already_loaded(self): """Test Credentials.check_activated() already loaded.""" c = Credentials.get_current() c.activation = Activation('some_email', 'some_code', True) with patch('streamlit.credentials._exit') as p: c.check_activated() p.assert_not_called()
def test_Credentials_save(self): """Test Credentials.save().""" c = Credentials.get_current() c.activation = Activation("some_email", True) truth = textwrap.dedent( """ [general] email = "some_email" """ ).lstrip() truth2 = textwrap.dedent( """ [general] email = "some_email" """ ).lstrip() m = mock_open() with patch("streamlit.credentials.open", m, create=True) as m: c.save() if sys.version_info >= (3, 0): m.return_value.write.assert_called_once_with(truth) else: m.return_value.write.assert_called_once_with(truth2)
def test_Credentials_get_current(self): """Test Credentials.get_current.""" Credentials._singleton = None c = Credentials.get_current() self.assertEqual(Credentials._singleton, c)
def test_Credentials_constructor(self): """Test Credentials constructor.""" c = Credentials() self.assertEqual(c._conf_file, "/mock/home/folder/.streamlit/credentials.toml") self.assertEqual(c.activation, None)
def _maybe_enqueue_initialize_message(self): if self._sent_initialize_message: return self._sent_initialize_message = True msg = ForwardMsg() imsg = msg.initialize imsg.config.sharing_enabled = (config.get_option('global.sharingMode') != 'off') LOGGER.debug('New browser connection: sharing_enabled=%s', imsg.config.sharing_enabled) imsg.config.gather_usage_stats = ( config.get_option('browser.gatherUsageStats')) LOGGER.debug('New browser connection: gather_usage_stats=%s', imsg.config.gather_usage_stats) imsg.environment_info.streamlit_version = __version__ imsg.environment_info.python_version = ('.'.join( map(str, sys.version_info))) imsg.session_state.run_on_save = self._run_on_save imsg.session_state.report_is_running = ( self._state == ReportSessionState.REPORT_IS_RUNNING) imsg.user_info.installation_id = __installation_id__ imsg.user_info.email = Credentials.get_current().activation.email self.enqueue(msg)
def test_Credentials_check_activated_already_loaded(self): """Test Credentials.check_activated() already loaded.""" c = Credentials.get_current() c.activation = Activation("some_email", True) with patch("streamlit.credentials._exit") as p: c._check_activated(auto_resolve=False) p.assert_not_called()
def test_Credentials_check_activated_false(self): """Test Credentials.check_activated() not activated.""" c = Credentials.get_current() c.activation = Activation("some_email", False) with patch("streamlit.credentials._exit") as p: c._check_activated(auto_resolve=False) p.assert_called_once_with("Activation email not valid.")
def _maybe_enqueue_initialize_message(self): if self._sent_initialize_message: return self._sent_initialize_message = True msg = protobuf.ForwardMsg() imsg = msg.initialize imsg.sharing_enabled = (config.get_option('global.sharingMode') != 'off') LOGGER.debug('New browser connection: sharing_enabled=%s', msg.initialize.sharing_enabled) imsg.gather_usage_stats = ( config.get_option('browser.gatherUsageStats')) LOGGER.debug('New browser connection: gather_usage_stats=%s', msg.initialize.gather_usage_stats) imsg.streamlit_version = __version__ imsg.session_state.run_on_save = self._scriptrunner.run_on_save imsg.session_state.report_is_running = self._scriptrunner.is_running() imsg.user_info.installation_id = __installation_id__ imsg.user_info.email = Credentials.get_current().activation.email self.enqueue(msg)
def test_Credentials_check_activated_error(self): """Test Credentials.check_activated() has an error.""" c = Credentials.get_current() c.activation = Activation("some_email", True) with patch.object(c, "load", side_effect=Exception( "Some error")), patch("streamlit.credentials._exit") as p: c._check_activated(auto_resolve=False) p.assert_called_once_with("Some error")
def test_Credentials_load_twice(self): """Test Credentials.load() called twice.""" c = Credentials.get_current() c.activation = Activation("some_email", True) with patch("streamlit.credentials.LOGGER") as p: c.load() p.error.assert_called_once_with( "Credentials already loaded. Not rereading file.")
def test_Credentials_check_activated_error(self): """Test Credentials.check_activated() has an error.""" c = Credentials.get_current() c.activation = Activation('some_email', 'some_code', True) with patch.object(c, 'load', side_effect=Exception( 'Some error')), patch('streamlit.credentials._exit') as p: c.check_activated() p.assert_called_once_with('Some error')
def test_Credentials_activate_already_activated(self): """Test Credentials.activate() already activated.""" c = Credentials.get_current() c.activation = Activation("some_email", True) with patch("streamlit.credentials.LOGGER") as p: with pytest.raises(SystemExit): c.activate() self.assertEqual(p.error.call_count, 2) self.assertEqual(p.error.call_args_list[1], call("Already activated"))
def test_Credentials_activate_already_activated_not_valid(self): """Test Credentials.activate() already activated but not valid.""" c = Credentials.get_current() c.activation = Activation("some_email", False) with patch("streamlit.credentials.LOGGER") as p: with pytest.raises(SystemExit): c.activate() self.assertEqual(p.error.call_count, 2) self.assertEqual( str(p.error.call_args_list[1])[0:27], "call('Activation not valid.")
def test_Credentials_load_file_not_found(self): """Test Credentials.load() with FileNotFoundError.""" with patch("streamlit.credentials.open") as m: m.side_effect = FileNotFoundError() c = Credentials.get_current() c.activation = None with pytest.raises(RuntimeError) as e: c.load() self.assertEqual( str(e.value), 'Credentials not found. Please run "streamlit activate".')
def test_Credentials_load_empty(self): """Test Credentials.load() with empty email""" data = textwrap.dedent(""" [general] email = "" """).strip() m = mock_open(read_data=data) with patch("streamlit.credentials.open", m, create=True): c = Credentials.get_current() c.load() self.assertEqual("", c.activation.email)
def test_Credentials_load(self): """Test Credentials.load().""" data = textwrap.dedent(''' [general] code = "ARzVsqhSB5i" email = "*****@*****.**" ''').strip() m = mock_open(read_data=data) with patch('streamlit.credentials.open', m, create=True) as m: c = Credentials.get_current() c.load() self.assertEqual(c.activation.email, '*****@*****.**') self.assertEqual(c.activation.code, None)
def _main_run(file, args=None): if args is None: args = [] # Set a global flag indicating that we're "within" streamlit. streamlit._is_running_with_streamlit = True # Check credentials. Credentials.get_current().check_activated(auto_resolve=True) # Notify if streamlit is out of date. if version.should_show_new_version_notice(): click.echo(NEW_VERSION_TEXT) # We don't use args ourselves. We just allow people to pass them so their # script can handle them via sys.argv or whatever. # IMPORTANT: This means we should treat argv carefully inside our code! import sys sys.argv = [file] + list(args) bootstrap.run(file)
def test_Credentials_activate(self): """Test Credentials.activate()""" c = Credentials.get_current() c.activation = None with patch.object( c, "load", side_effect=RuntimeError("Some error") ), patch.object(c, "save") as patched_save, patch(PROMPT) as patched_prompt: patched_prompt.side_effect = ["*****@*****.**"] c.activate() patched_save.assert_called_once() self.assertEqual(c.activation.email, "*****@*****.**") self.assertEqual(c.activation.is_valid, True)
def test_Credentials_activate(self): """Test Credentials.activate()""" c = Credentials.get_current() c.activation = None with patch.object( c, 'load', side_effect=RuntimeError('Some error')), patch.object( c, 'save') as s, patch(INPUT) as p: p.side_effect = ['ARzVsqhSB5i', '*****@*****.**'] c.activate() s.assert_called_once() self.assertEqual(c.activation.code, None) self.assertEqual(c.activation.email, '*****@*****.**') self.assertEqual(c.activation.is_valid, True)
def test_Credentials_load_permission_denied(self): """Test Credentials.load() with Perission denied.""" with patch("streamlit.credentials.open") as m: m.side_effect = PermissionError( "[Errno 13] Permission denied: ~/.streamlit/credentials.toml") c = Credentials.get_current() c.activation = None with pytest.raises(Exception) as e: c.load() self.assertEqual( str(e.value).split(":")[0], "\nUnable to load credentials from " "/mock/home/folder/.streamlit/credentials.toml.\n" 'Run "streamlit reset" and try again.\n', )
def test_Credentials_load_permission_denied(self): """Test Credentials.load() with Perission denied.""" if sys.version_info < (3, 0): return with patch('streamlit.credentials.open') as m: m.side_effect = PermissionError( '[Errno 13] Permission denied: ~/.streamlit/credentials.toml') c = Credentials.get_current() c.activation = None with pytest.raises(Exception) as e: c.load() self.assertEqual( str(e.value).split(':')[0], '\nUnable to load credentials from ' '/mock/home/folder/.streamlit/credentials.toml.\n' 'Run "streamlit reset" and try again.\n')