def test_project_with_connected_account(self): env = EnvironmentVarGuard() env.set('KAGGLE_USER_SECRETS_TOKEN', 'foobar') with env: client = bigquery.Client( project='ANOTHER_PROJECT', credentials=KaggleKernelCredentials()) self._test_proxy(client, should_use_proxy=False)
def test_project_with_connected_account_default_credentials(self): env = EnvironmentVarGuard() env.set('KAGGLE_USER_SECRETS_TOKEN', 'foobar') env.set('KAGGLE_KERNEL_INTEGRATIONS', 'BIGQUERY') with env: client = bigquery.Client(project='ANOTHER_PROJECT') self._test_proxy(client, should_use_proxy=False)
def test_proxy_with_kwargs(self): env = EnvironmentVarGuard() env.unset('KAGGLE_USER_SECRETS_TOKEN') with env: client = bigquery.Client( default_query_job_config=bigquery.QueryJobConfig(maximum_bytes_billed=1e9)) self._test_proxy(client, should_use_proxy=True)
def test_project_with_connected_account_unrelated_integrations(self): env = EnvironmentVarGuard() env.set('KAGGLE_USER_SECRETS_TOKEN', 'foobar') env.set('KAGGLE_KERNEL_INTEGRATIONS', 'GCS:ANOTHER_ONE') with env: client = bigquery.Client( project='ANOTHER_PROJECT', credentials=KaggleKernelCredentials()) self._test_proxy(client, should_use_proxy=False)
class EnvironGuard(object): def setUp(self): super(EnvironGuard, self).setUp() self.environ = EnvironmentVarGuard() def tearDown(self): self.environ.__exit__() super(EnvironGuard, self).tearDown()
def test_no_project_with_connected_account(self): env = EnvironmentVarGuard() env.set('KAGGLE_USER_SECRETS_TOKEN', 'foobar') env.set('KAGGLE_KERNEL_INTEGRATIONS', 'BIGQUERY') with env: with self.assertRaises(DefaultCredentialsError): # TODO(vimota): Handle this case, either default to Kaggle Proxy or use some default project # by the user or throw a custom exception. client = bigquery.Client() self._test_proxy(client, should_use_proxy=False)
def test_simultaneous_clients(self): env = EnvironmentVarGuard() env.set('KAGGLE_USER_SECRETS_TOKEN', 'foobar') with env: proxy_client = bigquery.Client() self._test_proxy(proxy_client, should_use_proxy=True) bq_client = bigquery.Client( project='ANOTHER_PROJECT', credentials=KaggleKernelCredentials()) self._test_proxy(bq_client, should_use_proxy=False) # Verify that proxy client is still going to proxy to ensure global Connection # isn't being modified. self._test_proxy(proxy_client, should_use_proxy=True)
def setUp(self): self.env = EnvironmentVarGuard() self.env.set('SECRET_KEY', 'xoxo') self.env.set( 'DATABASE_URL', 'mysql2://myuser:mypass@myhost:3306/my_database_name' ) self.env.set('STATIC', '/path/to/static')
def _test_client(self, client_func, expected_path, expected_body, secret=None, success=True): _request = {} class AccessTokenHandler(UserSecretsHTTPHandler): def set_request(self): _request['path'] = self.path content_len = int(self.headers.get('Content-Length')) _request['body'] = json.loads(self.rfile.read(content_len)) _request['headers'] = self.headers def get_response(self): if success: return {'result': {'secret': secret, 'secretType': 'refreshToken', 'secretProvider': 'google', 'expiresInSeconds': 3600}, 'wasSuccessful': "true"} else: return {'wasSuccessful': "false"} env = EnvironmentVarGuard() env.set(_KAGGLE_USER_SECRETS_TOKEN_ENV_VAR_NAME, _TEST_JWT) with env: with HTTPServer((self.SERVER_ADDRESS.hostname, self.SERVER_ADDRESS.port), AccessTokenHandler) as httpd: threading.Thread(target=httpd.serve_forever).start() try: client_func() finally: httpd.shutdown() path, headers, body = _request['path'], _request['headers'], _request['body'] self.assertEqual( path, expected_path, msg="Fake server did not receive the right request from the UserSecrets client.") self.assertEqual( body, expected_body, msg="Fake server did not receive the right body from the UserSecrets client.")
def test_getuserbase(self): site.USER_BASE = None user_base = site.getuserbase() # the call sets site.USER_BASE self.assertEqual(site.USER_BASE, user_base) # let's set PYTHONUSERBASE and see if it uses it site.USER_BASE = None import sysconfig sysconfig._CONFIG_VARS = None with EnvironmentVarGuard() as environ: environ['PYTHONUSERBASE'] = 'xoxo' self.assertTrue(site.getuserbase().startswith('xoxo'), site.getuserbase())
def test_new_rmc_for_non_existent_model(self): with EnvironmentVarGuard() as env: env['MORANGO_SYSTEM_ID'] = 'new_sys_id' (new_id, _) = InstanceIDModel.get_or_create_current_instance(clear_cache=True) new_fac = FacilityModelFactory(name="college") self.mc.serialize_into_store() new_rmc = RecordMaxCounter.objects.get( instance_id=new_id.id, store_model_id=new_fac.id ) new_store_record = Store.objects.get(id=new_fac.id) self.assertNotEqual(new_id.id, self.current_id.id) self.assertEqual(new_store_record.last_saved_instance, new_rmc.instance_id) self.assertEqual(new_store_record.last_saved_counter, new_rmc.counter)
def test_magics_with_connected_account_default_credentials(self): env = EnvironmentVarGuard() env.set('KAGGLE_USER_SECRETS_TOKEN', 'foobar') env.set('KAGGLE_KERNEL_INTEGRATIONS', 'BIGQUERY') with env: import sitecustomize sitecustomize.init() from google.cloud.bigquery import magics self.assertEqual(type(magics.context._credentials), KaggleKernelCredentials) magics.context.credentials = None
def test_user_provided_credentials(self): credentials = _make_credentials() env = EnvironmentVarGuard() env.set('KAGGLE_USER_SECRETS_TOKEN', 'foobar') env.set('KAGGLE_KERNEL_INTEGRATIONS', 'VISION') with env: init_vision() client = vision.ImageAnnotatorClient(credentials=credentials) self.assertNotIsInstance(client.credentials, KaggleKernelCredentials) self.assertIsNotNone(client.credentials)
def test_project_with_connected_account_unrelated_integrations( self, mock_access_token): env = EnvironmentVarGuard() env.set('KAGGLE_USER_SECRETS_TOKEN', 'foobar') env.set('KAGGLE_KERNEL_INTEGRATIONS', 'GCS:ANOTHER_ONE') with env: client = bigquery.Client( project='ANOTHER_PROJECT', credentials=KaggleKernelCredentials(), client_options={"api_endpoint": TestBigQuery.API_BASE_URL}) self._test_integration(client)
def test_user_provided_credentials_v2(self): credentials = _make_credentials() env = EnvironmentVarGuard() env.set('KAGGLE_USER_SECRETS_TOKEN', 'foobar') env.set('KAGGLE_KERNEL_INTEGRATIONS', 'CLOUDAI') with env: init_translation_v2() client = translate_v2.Client(credentials=credentials) self.assertIsNotNone(client.credentials) self.assertNotIsInstance(client.credentials, KaggleKernelCredentials)
def test_no_project_with_connected_account(self): env = EnvironmentVarGuard() env.set('KAGGLE_USER_SECRETS_TOKEN', 'foobar') env.set('KAGGLE_KERNEL_INTEGRATIONS', 'BIGQUERY') with env: with self.assertRaises(DefaultCredentialsError): # TODO(vimota): Handle this case, either default to Kaggle Proxy or use some default project # by the user or throw a custom exception. client = bigquery.Client( client_options={"api_endpoint": TestBigQuery.API_BASE_URL}) self._test_integration(client)
def test_user_provided_credentials(self): credentials = _make_credentials() env = EnvironmentVarGuard() env.set('KAGGLE_USER_SECRETS_TOKEN', 'foobar') env.set('KAGGLE_KERNEL_INTEGRATIONS', 'AUTOML') with env: init_automl() client = automl.AutoMlClient(credentials=credentials) self.assertNotIsInstance(client.credentials, KaggleKernelCredentials) self.assertIsNotNone(client.credentials)
def test_default_credentials_gcs_enabled(self): env = EnvironmentVarGuard() env.set('KAGGLE_USER_SECRETS_TOKEN', 'foobar') env.set('KAGGLE_KERNEL_INTEGRATIONS', 'GCS') with env: init_gcs() client = storage.Client(project="xyz") self.assertIsInstance(client._credentials, KaggleKernelCredentials) self.assertTrue( client._connection.user_agent.startswith( "kaggle-gcp-client/1.0"))
def test_user_provided_credentials(self): credentials = _make_credentials() env = EnvironmentVarGuard() env.set('KAGGLE_USER_SECRETS_TOKEN', 'foobar') env.set('KAGGLE_KERNEL_INTEGRATIONS', 'CLOUDAI') with env: init_natural_language() client = language.LanguageServiceClient(credentials=credentials) self.assertIsNotNone(client.credentials) self.assertNotIsInstance(client.credentials, KaggleKernelCredentials)
def _check_sys(self, ev, cond, sv, val=sys.executable + 'dummy'): with EnvironmentVarGuard() as evg: subpc = [ str(sys.executable), '-c', 'import sys; sys.exit(2 if "%s" %s %s else 3)' % (val, cond, sv) ] # ensure environment variable does not exist evg.unset(ev) # test that test on sys.xxx normally fails rc = subprocess.call(subpc) self.assertEqual(rc, 3, "expected %s not %s %s" % (ev, cond, sv)) # set environ variable evg.set(ev, val) # test that sys.xxx has been influenced by the environ value rc = subprocess.call(subpc) self.assertEqual(rc, 2, "expected %s %s %s" % (ev, cond, sv))
def setUp(self): for obj in ('ubiquity.misc.execute', 'ubiquity.misc.execute_root'): patcher = mock.patch(obj) patcher.start() self.addCleanup(patcher.stop) ubi_language = plugin_manager.load_plugin('ubi-language') self.controller = mock.Mock() self.controller.oem_user_config = False self.controller.oem_config = False self.ubi_language = ubi_language # Set the environment variable needed in order for PageGtk to hook up # the Try Xenta OS button with the appropriate action. with EnvironmentVarGuard() as environ: environ['UBIQUITY_GREETER'] = '1' self.gtk = self.ubi_language.PageGtk(self.controller)
def test_ctr(self): credentials = _make_credentials() env = EnvironmentVarGuard() env.set('KAGGLE_USER_SECRETS_TOKEN', 'foobar') env.set('KAGGLE_KERNEL_INTEGRATIONS', 'GCS') with env: init_gcs() client = storage.Client(project="xyz", credentials=credentials) self.assertEqual(client.project, "xyz") self.assertNotIsInstance(client._credentials, KaggleKernelCredentials) self.assertIsNotNone(client._credentials)
class ParentTest(TestCase): def create_app(self): self.env = EnvironmentVarGuard() self.env.set('DYNAMO_TABLE', 'test_table') self.env.set('AWS_REGION', 'us-west-1') self.env.set('PERSONALIZE_SRC_FILE', '../../app/personalize/rsvp_content.yaml') with self.env: from config import Config from tests import context app = context.app.create_app(Config) return app
def test_user_provided_credentials(self): credentials = _make_credentials() env = EnvironmentVarGuard() env.set('KAGGLE_USER_SECRETS_TOKEN', 'foobar') env.set('KAGGLE_KERNEL_INTEGRATIONS', 'VIDEO_INTELLIGENCE') with env: init_video_intelligence() client = videointelligence.VideoIntelligenceServiceClient( credentials=credentials) self.assertNotIsInstance(client.credentials, KaggleKernelCredentials) self.assertIsNotNone(client.credentials)
def test_legacy_AUTOML_variable_v1beta1_client(self): """ Tests previous KAGGLE_KERNEL_INTEGRATIONS="AUTOML" environment setting """ env = EnvironmentVarGuard() env.set('KAGGLE_USER_SECRETS_TOKEN', 'foobar') env.set('KAGGLE_KERNEL_INTEGRATIONS', 'AUTOML') with env: prediction_client = automl_v1beta1.PredictionServiceClient() self.assertIsNotNone(prediction_client.credentials) self.assertIsInstance(prediction_client.credentials, KaggleKernelCredentials) self.assertTrue(prediction_client._connection.user_agent.startswith("kaggle-gcp-client/1.0"))
def test_imp_module(self): # Verify that the imp module can correctly load and find .py files # XXX (ncoghlan): It would be nice to use support.CleanImport # here, but that breaks because the os module registers some # handlers in copy_reg on import. Since CleanImport doesn't # revert that registration, the module is left in a broken # state after reversion. Reinitialising the module contents # and just reverting os.environ to its previous state is an OK # workaround orig_path = os.path orig_getenv = os.getenv with EnvironmentVarGuard(): x = imp.find_module("os") self.addCleanup(x[0].close) new_os = imp.load_module("os", *x) self.assertIs(os, new_os) self.assertIs(orig_path, new_os.path) self.assertIsNot(orig_getenv, new_os.getenv)
def test_jwt_validator_with_offline(self): # given env = EnvironmentVarGuard() with env: env.set('IS_OFFLINE', 'any value') env.set('LOCAL_USER_ID', 'any user') # when validator = EventValidator() response = validator.get_user_sub_from_event({}) # then self.assertEqual(response, 'any user')
def test_project_with_connected_account_default_credentials( self, mock_access_token): env = EnvironmentVarGuard() env.set('KAGGLE_USER_SECRETS_TOKEN', 'foobar') env.set('KAGGLE_KERNEL_INTEGRATIONS', 'BIGQUERY') with env: client = bigquery.Client( project='ANOTHER_PROJECT', client_options={"api_endpoint": TestBigQuery.API_BASE_URL}) self.assertTrue( client._connection.user_agent.startswith( "kaggle-gcp-client/1.0")) self._test_integration(client)
def test_default_credentials_automl_client(self): env = EnvironmentVarGuard() env.set('KAGGLE_USER_SECRETS_TOKEN', 'foobar') env.set('KAGGLE_KERNEL_INTEGRATIONS', 'AUTOML') with env: init_automl() automl_client = automl.AutoMlClient() self.assertIsNotNone(automl_client.credentials) self.assertIsInstance(automl_client.credentials, KaggleKernelCredentials) self.assertTrue( automl_client._connection.user_agent.startswith( "kaggle-gcp-client/1.0"))
def test_monkeypatching_succeed(self): env = EnvironmentVarGuard() env.set('KAGGLE_USER_SECRETS_TOKEN', 'foobar') env.set('KAGGLE_KERNEL_INTEGRATIONS', 'CLOUDAI') with env: init_translation_v2() init_translation_v3() # Translation V2 client2 = translate_v2.Client.__init__ self.assertTrue("kaggle_gcp" in inspect.getsourcefile(client2)) # Translation V3 client3 = translate.TranslationServiceClient.__init__ self.assertTrue("kaggle_gcp" in inspect.getsourcefile(client3))
def setUpClass(cls) -> None: cls.env = EnvironmentVarGuard() if os.getenv("IS_LOCAL", True): cls.env.set('DYNAMO_TABLE', 'test_table') cls.env.set('AWS_REGION', 'us-west-1') cls.env.set('AWS_ENDPOINT_URL', 'http://localhost:7012') cls.env.set('AWS_ACCESS_KEY_ID', 'testing') cls.env.set('AWS_SECRET_ACCESS_KEY', 'testing') cls.env.set('AWS_SECURITY_TOKEN', 'testing') cls.env.set('AWS_SESSION_TOKEN', 'testing') cls.env.set('PERSONALIZE_SRC_FILE', 'app/personalize/rsvp_content.yaml') cls.moto_app = create_backend_app("dynamodb2") cls.moto_thread = threading.Thread(target=cls.moto_app.run, args=("localhost", 7012), kwargs={"use_reloader": False}) cls.moto_thread.setDaemon(True) cls.moto_thread.start()
def test_run_not_fail_on_debug(self, mock_requests): """ do a run with DEIS_DEBUG on - https://github.com/deis/controller/issues/583 """ env = EnvironmentVarGuard() env['DEIS_DEBUG'] = 'true' url = '/v2/apps' response = self.client.post(url) self.assertEqual(response.status_code, 201, response.data) app_id = response.data['id'] app = App.objects.get(id=app_id) # dockerfile + procfile worflow build = Build.objects.create( owner=self.user, app=app, image="qwerty", procfile={ 'web': 'node server.js', 'worker': 'node worker.js' }, dockerfile='foo', sha='somereallylongsha' ) # create an initial release Release.objects.create( version=2, owner=self.user, app=app, config=app.config_set.latest(), build=build ) # create a run pod url = "/v2/apps/{app_id}/run".format(**locals()) body = {'command': 'echo hi'} response = self.client.post(url, body) self.assertEqual(response.status_code, 200, response.data) data = App.objects.get(id=app_id) entrypoint, _ = data._get_command_run('echo hi') self.assertEqual(entrypoint, '/bin/bash')
def test_consistent_0_5_instance_id(self, *args): """ If this test fails, it means we've changed the way Instance IDs are calculated in an undesirable way. """ with EnvironmentVarGuard() as env: env["MORANGO_SYSTEM_ID"] = "magicsysid" DatabaseIDModel.objects.all().update(current=False) database_id = DatabaseIDModel.objects.create( id="7fe445b75cea11858c00fb97bdee8878", current=True ).id self.assertEqual(get_0_5_system_id(), "54940f560a55bbf7d86b") self.assertEqual(get_0_5_mac_address(), "804f4c20d3b2b5a29b95") instance, _ = InstanceIDModel.get_or_create_current_instance(clear_cache=True) self.assertEqual(instance.id, "e45c06595d820f4581e0c82930359592")
def _test_client(self, client_func, expected_path, expected_body, is_tpu=True, success=True): _request = {} class GetGcsPathHandler(GcsDatasetsHTTPHandler): def set_request(self): _request['path'] = self.path content_len = int(self.headers.get('Content-Length')) _request['body'] = json.loads(self.rfile.read(content_len)) _request['headers'] = self.headers def get_response(self): if success: gcs_path = _TPU_GCS_BUCKET if is_tpu else _AUTOML_GCS_BUCKET return {'result': { 'destinationBucket': gcs_path, 'destinationPath': None}, 'wasSuccessful': "true"} else: return {'wasSuccessful': "false"} env = EnvironmentVarGuard() env.set(_KAGGLE_USER_SECRETS_TOKEN_ENV_VAR_NAME, _TEST_JWT) if is_tpu: env.set(_KAGGLE_TPU_NAME_ENV_VAR_NAME, 'FAKE_TPU') with env: with HTTPServer((self.SERVER_ADDRESS.hostname, self.SERVER_ADDRESS.port), GetGcsPathHandler) as httpd: threading.Thread(target=httpd.serve_forever).start() try: client_func() finally: httpd.shutdown() path, headers, body = _request['path'], _request['headers'], _request['body'] self.assertEqual( path, expected_path, msg="Fake server did not receive the right request from the KaggleDatasets client.") self.assertEqual( body, expected_body, msg="Fake server did not receive the right body from the KaggleDatasets client.") self.assertIn('Content-Type', headers.keys(), msg="Fake server did not receive a Content-Type header from the KaggleDatasets client.") self.assertEqual('application/json', headers.get('Content-Type'), msg="Fake server did not receive an application/json content type header from the KaggleDatasets client.") self.assertIn('Authorization', headers.keys(), msg="Fake server did not receive an Authorization header from the KaggleDatasets client.") self.assertEqual(f'Bearer {_TEST_JWT}', headers.get('Authorization'), msg="Fake server did not receive the right Authorization header from the KaggleDatasets client.")
def test_user_provided_credentials(self): credentials = _make_credentials() env = EnvironmentVarGuard() env.set('KAGGLE_USER_SECRETS_TOKEN', 'foobar') env.set('KAGGLE_KERNEL_INTEGRATIONS', 'CLOUDAI') with env: from google.cloud import aiplatform init_ucaip() aiplatform.init(credentials=credentials) self.assertNotIsInstance( aiplatform.initializer.global_config.credentials, KaggleKernelCredentials) self.assertIsNotNone( aiplatform.initializer.global_config.credentials)
def test_osx_cc_overrides_ldshared(self): # Issue #18080: # ensure that setting CC env variable also changes default linker def gcv(v): if v == 'LDSHARED': return 'gcc-4.2 -bundle -undefined dynamic_lookup ' return 'gcc-4.2' def gcvs(*args, _orig=sysconfig.get_config_vars): if args: return list(map(sysconfig.get_config_var, args)) return _orig() sysconfig.get_config_var = gcv sysconfig.get_config_vars = gcvs with EnvironmentVarGuard() as env: env['CC'] = 'my_cc' del env['LDSHARED'] sysconfig.customize_compiler(self.cc) self.assertEqual(self.cc.linker_so[0], 'my_cc')
def test_url_downloadable(self): from UpdateManager.Core.utils import url_downloadable with EnvironmentVarGuard() as environ: # ensure that $no_proxy doesn't prevent us from accessing # localhost through proxy try: del environ["no_proxy"] except KeyError: pass logging.debug("proxy 1") environ["http_proxy"] = "http://localhost:%s/" % self.port install_opener(None) self.assertTrue( url_downloadable("http://archive.ubuntu.com", logging.debug), "download with proxy %s failed" % environ["http_proxy"]) logging.debug("proxy 2") environ["http_proxy"] = "http://localhost:%s" % self.port install_opener(None) self.assertTrue( url_downloadable("http://archive.ubuntu.com", logging.debug), "download with proxy %s failed" % environ["http_proxy"]) logging.debug("no proxy") del environ["http_proxy"] install_opener(None) self.assertTrue( url_downloadable("http://archive.ubuntu.com", logging.debug), "download with no proxy failed") logging.debug("no proxy, no valid adress") self.assertFalse( url_downloadable("http://archive.ubuntu.com/xxx", logging.debug), "download with no proxy failed") logging.debug("proxy, no valid adress") environ["http_proxy"] = "http://localhost:%s" % self.port install_opener(None) self.assertFalse( url_downloadable("http://archive.ubuntu.com/xxx", logging.debug), "download with no proxy failed")
class KeyserverTestCase(AioHTTPTestCase): """KeyServer. Testing keyserver by importing the routes and mocking the innerworkings. """ env = EnvironmentVarGuard() env.set('LEGA_PASSWORD', 'value') env.set('KEYS_PASSWORD', 'value') with env: _cache = Cache() async def get_application(self): """Retrieve the routes to a mock server.""" app = web.Application() app.router.add_routes(routes) return app @unittest_run_loop async def test_health(self): """Simplest test the health endpoint.""" resp = await self.client.request("GET", "/health") assert resp.status == 200 @unittest_run_loop async def test_forbidden(self): """Request a forbidden if type (public/private) that does not exist.""" rsa_resp = await self.client.request("GET", "/active/no_key") assert rsa_resp.status == 403 @unittest_run_loop async def test_bad_request(self): """Request a key type that does not exist.""" rsa_resp = await self.client.request("GET", "/active/private") assert rsa_resp.status == 404 @unittest_run_loop async def test_retrieve_not_found(self): """Retrieve Endpoint not found. In this case PGP key.""" pgp_resp = await self.client.request("GET", "/retrieve/pgp/74EACHW8") assert pgp_resp.status == 403
def test_set_default_org(self): """ The EnvironmentProjectKeychain does not persist default org settings """ with EnvironmentVarGuard() as env: self._clean_env(env) org_config = self.org_config.config.copy() self.env.set( '{}test'.format(self.keychain_class.org_var_prefix), json.dumps(org_config) ) env.set( self.keychain_class.app_var, json.dumps(self.connected_app_config.config) ) keychain = self.keychain_class(self.project_config, self.key) keychain.set_default_org('test') expected_org_config = self.org_config.config.copy() expected_org_config['default'] = True self.assertEquals( None, keychain.get_default_org()[1], )
class TestEnv(unittest.TestCase): def setUp(self): self.env = EnvironmentVarGuard() self.env.set('SECRET_KEY', 'xoxo') self.env.set( 'DATABASE_URL', 'mysql2://myuser:mypass@myhost:3306/my_database_name' ) self.env.set('STATIC', '/path/to/static') def test_secret_key(self): from project_name import settings self.assertEqual(settings.SECRET_KEY,'xoxo') def test_db_url(self): from project_name import settings self.assertEqual( settings.DATABASES['default']['HOST'], 'myhost' ) def test_db_name(self): from project_name import settings self.assertEqual( settings.DATABASES['default']['NAME'], 'my_database_name' ) def test_static(self): from project_name import settings self.assertEqual( settings.STATIC_ROOT, '/path/to/static' ) self.assertEqual( settings.STATICFILES_STORAGE, 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' )
def setUp(self): super(EnvironGuard, self).setUp() self.environ = EnvironmentVarGuard()
def test_proxy_using_library(self): env = EnvironmentVarGuard() env.unset('KAGGLE_USER_SECRETS_TOKEN') with env: client = PublicBigqueryClient() self._test_proxy(client, should_use_proxy=True)
def setUp(self): self.env = EnvironmentVarGuard() if "POSIXLY_CORRECT" in self.env: del self.env["POSIXLY_CORRECT"]
class GetoptTests(unittest.TestCase): def setUp(self): self.env = EnvironmentVarGuard() if "POSIXLY_CORRECT" in self.env: del self.env["POSIXLY_CORRECT"] def tearDown(self): self.env.__exit__() del self.env def assertError(self, *args, **kwargs): self.assertRaises(getopt.GetoptError, *args, **kwargs) def test_short_has_arg(self): self.assertTrue(getopt.short_has_arg('a', 'a:')) self.assertFalse(getopt.short_has_arg('a', 'a')) self.assertError(getopt.short_has_arg, 'a', 'b') def test_long_has_args(self): has_arg, option = getopt.long_has_args('abc', ['abc=']) self.assertTrue(has_arg) self.assertEqual(option, 'abc') has_arg, option = getopt.long_has_args('abc', ['abc']) self.assertFalse(has_arg) self.assertEqual(option, 'abc') has_arg, option = getopt.long_has_args('abc', ['abcd']) self.assertFalse(has_arg) self.assertEqual(option, 'abcd') self.assertError(getopt.long_has_args, 'abc', ['def']) self.assertError(getopt.long_has_args, 'abc', []) self.assertError(getopt.long_has_args, 'abc', ['abcd','abcde']) def test_do_shorts(self): opts, args = getopt.do_shorts([], 'a', 'a', []) self.assertEqual(opts, [('-a', '')]) self.assertEqual(args, []) opts, args = getopt.do_shorts([], 'a1', 'a:', []) self.assertEqual(opts, [('-a', '1')]) self.assertEqual(args, []) #opts, args = getopt.do_shorts([], 'a=1', 'a:', []) #self.assertEqual(opts, [('-a', '1')]) #self.assertEqual(args, []) opts, args = getopt.do_shorts([], 'a', 'a:', ['1']) self.assertEqual(opts, [('-a', '1')]) self.assertEqual(args, []) opts, args = getopt.do_shorts([], 'a', 'a:', ['1', '2']) self.assertEqual(opts, [('-a', '1')]) self.assertEqual(args, ['2']) self.assertError(getopt.do_shorts, [], 'a1', 'a', []) self.assertError(getopt.do_shorts, [], 'a', 'a:', []) def test_do_longs(self): opts, args = getopt.do_longs([], 'abc', ['abc'], []) self.assertEqual(opts, [('--abc', '')]) self.assertEqual(args, []) opts, args = getopt.do_longs([], 'abc=1', ['abc='], []) self.assertEqual(opts, [('--abc', '1')]) self.assertEqual(args, []) opts, args = getopt.do_longs([], 'abc=1', ['abcd='], []) self.assertEqual(opts, [('--abcd', '1')]) self.assertEqual(args, []) opts, args = getopt.do_longs([], 'abc', ['ab', 'abc', 'abcd'], []) self.assertEqual(opts, [('--abc', '')]) self.assertEqual(args, []) # Much like the preceding, except with a non-alpha character ("-") in # option name that precedes "="; failed in # http://python.org/sf/126863 opts, args = getopt.do_longs([], 'foo=42', ['foo-bar', 'foo=',], []) self.assertEqual(opts, [('--foo', '42')]) self.assertEqual(args, []) self.assertError(getopt.do_longs, [], 'abc=1', ['abc'], []) self.assertError(getopt.do_longs, [], 'abc', ['abc='], []) def test_getopt(self): # note: the empty string between '-a' and '--beta' is significant: # it simulates an empty string option argument ('-a ""') on the # command line. cmdline = ['-a', '1', '-b', '--alpha=2', '--beta', '-a', '3', '-a', '', '--beta', 'arg1', 'arg2'] opts, args = getopt.getopt(cmdline, 'a:b', ['alpha=', 'beta']) self.assertEqual(opts, [('-a', '1'), ('-b', ''), ('--alpha', '2'), ('--beta', ''), ('-a', '3'), ('-a', ''), ('--beta', '')]) # Note ambiguity of ('-b', '') and ('-a', '') above. This must be # accounted for in the code that calls getopt(). self.assertEqual(args, ['arg1', 'arg2']) self.assertError(getopt.getopt, cmdline, 'a:b', ['alpha', 'beta']) def test_gnu_getopt(self): # Test handling of GNU style scanning mode. cmdline = ['-a', 'arg1', '-b', '1', '--alpha', '--beta=2'] # GNU style opts, args = getopt.gnu_getopt(cmdline, 'ab:', ['alpha', 'beta=']) self.assertEqual(args, ['arg1']) self.assertEqual(opts, [('-a', ''), ('-b', '1'), ('--alpha', ''), ('--beta', '2')]) # recognize "-" as an argument opts, args = getopt.gnu_getopt(['-a', '-', '-b', '-'], 'ab:', []) self.assertEqual(args, ['-']) self.assertEqual(opts, [('-a', ''), ('-b', '-')]) # Posix style via + opts, args = getopt.gnu_getopt(cmdline, '+ab:', ['alpha', 'beta=']) self.assertEqual(opts, [('-a', '')]) self.assertEqual(args, ['arg1', '-b', '1', '--alpha', '--beta=2']) # Posix style via POSIXLY_CORRECT self.env["POSIXLY_CORRECT"] = "1" opts, args = getopt.gnu_getopt(cmdline, 'ab:', ['alpha', 'beta=']) self.assertEqual(opts, [('-a', '')]) self.assertEqual(args, ['arg1', '-b', '1', '--alpha', '--beta=2']) def test_libref_examples(self): s = """ Examples from the Library Reference: Doc/lib/libgetopt.tex An example using only Unix style options: >>> import getopt >>> args = '-a -b -cfoo -d bar a1 a2'.split() >>> args ['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2'] >>> optlist, args = getopt.getopt(args, 'abc:d:') >>> optlist [('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')] >>> args ['a1', 'a2'] Using long option names is equally easy: >>> s = '--condition=foo --testing --output-file abc.def -x a1 a2' >>> args = s.split() >>> args ['--condition=foo', '--testing', '--output-file', 'abc.def', '-x', 'a1', 'a2'] >>> optlist, args = getopt.getopt(args, 'x', [ ... 'condition=', 'output-file=', 'testing']) >>> optlist [('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x', '')] >>> args ['a1', 'a2'] """ import types m = types.ModuleType("libreftest", s) run_doctest(m, verbose)
def test_proxy_no_project(self): env = EnvironmentVarGuard() env.unset('KAGGLE_USER_SECRETS_TOKEN') with env: client = bigquery.Client() self._test_proxy(client, should_use_proxy=True)
def test_no_token_fails(self): env = EnvironmentVarGuard() env.unset(_KAGGLE_USER_SECRETS_TOKEN_ENV_VAR_NAME) with env: with self.assertRaises(CredentialError): client = UserSecretsClient()
def __init__(self): EnvironmentVarGuard.__init__(self) self._environ = self._environ.copy()
import unittest from test.support import EnvironmentVarGuard from environ import settings """ Unit tests """ class TestSettings(unittest.TestCase): def test_my_custom_param(self): self.assertEqual('Hello World!', settings('MY_CUSTOM_PARAM')) if __name__ == '__main__': env = EnvironmentVarGuard() env.set('SETTINGS_MODULE', '{{cookiecutter.repo_name}}.settings.unittest') with env: unittest.main()