def test_login(self): def _get_current_user(): return users.User('*****@*****.**', _user_id='111111111100000000001') request = HttpRequest() SessionMiddleware().process_request(request) # Make the damn sessions work request.session[BACKEND_SESSION_KEY] = 'djangae.contrib.gauth.datastore.backends.AppEngineUserAPIBackend' middleware = AuthenticationMiddleware() # Check that we're not logged in already user = get_user(request) self.assertFalse(user.is_authenticated()) # Check that running the middleware when the Google users API doesn't know the current # user still leaves us as an anonymous users. with sleuth.switch('djangae.contrib.gauth.middleware.users.get_current_user', lambda: None): middleware.process_request(request) # Check that the middleware successfully logged us in user = get_user(request) self.assertFalse(user.is_authenticated()) # Now check that when the Google users API *does* know who we are, that we are logged in. with sleuth.switch('djangae.contrib.gauth.middleware.users.get_current_user', _get_current_user): middleware.process_request(request) # Check that the middleware successfully logged us in user = get_user(request) self.assertTrue(user.is_authenticated()) self.assertEqual(user.email, '*****@*****.**') self.assertEqual(user.username, '111111111100000000001')
def test_user_email_update(self): """ Users can alter their Google account's primary email address. Make sure that we update it on the Django model. """ email = '*****@*****.**' user = users.User(email, _user_id='111111111100000000001') User = get_user_model() request = HttpRequest() SessionMiddleware().process_request(request) # Make the damn sessions work request.session[BACKEND_SESSION_KEY] = 'djangae.contrib.gauth_datastore.backends.AppEngineUserAPIBackend' middleware = AuthenticationMiddleware() with sleuth.switch('djangae.contrib.gauth.middleware.users.get_current_user', lambda: user): middleware.process_request(request) self.assertEqual(1, User.objects.count()) django_user = request.user self.assertEqual(email, django_user.email) new_email = '*****@*****.**' user = users.User(new_email, _user_id=user.user_id()) with sleuth.switch('djangae.contrib.gauth.middleware.users.get_current_user', lambda: user): middleware.process_request(request) self.assertEqual(1, User.objects.count()) django_user = request.user self.assertEqual(new_email, django_user.email) self.assertEqual(new_email.lower(), django_user.email_lower)
def test_user_id_switch(self): """ Users sometimes login with the same email, but a different google user id. We handle those cases by blanking out the email on the old user object and creating a new one with the new user id. """ email = '*****@*****.**' user1 = users.User(email, _user_id='111111111100000000001') user2 = users.User(email, _user_id='222222222200000000002') User = get_user_model() request = HttpRequest() SessionMiddleware().process_request(request) # Make the damn sessions work request.session[BACKEND_SESSION_KEY] = 'djangae.contrib.gauth.datastore.backends.AppEngineUserAPIBackend' middleware = AuthenticationMiddleware() with sleuth.switch('djangae.contrib.gauth.middleware.users.get_current_user', lambda: user1): middleware.process_request(request) self.assertEqual(1, User.objects.count()) django_user1 = request.user self.assertEqual(user1.user_id(), django_user1.username) self.assertEqual(user1.email(), django_user1.email) with sleuth.switch('djangae.contrib.gauth.middleware.users.get_current_user', lambda: user2): middleware.process_request(request) self.assertEqual(2, User.objects.count()) django_user2 = request.user self.assertEqual(user2.user_id(), django_user2.username) self.assertEqual(user2.email(), django_user2.email) django_user1 = User.objects.get(pk=django_user1.pk) self.assertEqual(django_user1.email, "")
def test_user_id_switch(self): """ Users sometimes login with the same email, but a different google user id. We handle those cases by blanking out the email on the old user object and creating a new one with the new user id. """ email = '*****@*****.**' user1 = users.User(email, _user_id='111111111100000000001') user2 = users.User(email, _user_id='222222222200000000002') User = get_user_model() request = HttpRequest() SessionMiddleware().process_request(request) # Make the damn sessions work request.session[BACKEND_SESSION_KEY] = 'djangae.contrib.gauth.datastore.backends.AppEngineUserAPIBackend' middleware = AuthenticationMiddleware() with sleuth.switch('djangae.contrib.gauth.middleware.users.get_current_user', lambda: user1): middleware.process_request(request) self.assertEqual(1, User.objects.count()) django_user1 = request.user self.assertEqual(user1.user_id(), django_user1.username) self.assertEqual(user1.email(), django_user1.email) with sleuth.switch('djangae.contrib.gauth.middleware.users.get_current_user', lambda: user2): middleware.process_request(request) self.assertEqual(2, User.objects.count()) django_user2 = request.user self.assertEqual(user2.user_id(), django_user2.username) self.assertEqual(user2.email(), django_user2.email) django_user1 = User.objects.get(pk=django_user1.pk) self.assertEqual(django_user1.email, None)
def test_account_switch(self): def _get_user_one(): return users.User('*****@*****.**', _user_id='111111111100000000001') def _get_user_two(): return users.User('*****@*****.**', _user_id='222222222200000000002') request = HttpRequest() SessionMiddleware().process_request( request) # Make the damn sessions work middleware = AuthenticationMiddleware() with sleuth.switch( 'djangae.contrib.gauth.middleware.users.get_current_user', _get_user_one): middleware.process_request(request) self.assertEqual(_get_user_one().user_id(), request.user.username) with sleuth.switch( 'djangae.contrib.gauth.middleware.users.get_current_user', _get_user_two): middleware.process_request(request) self.assertEqual(_get_user_two().user_id(), request.user.username)
def test_ok(self): """Lightweight end-to-end flow test of backup_datastore.""" with sleuth.switch( 'djangae.contrib.backup.tasks._get_authentication_credentials', lambda: app_engine.Credentials(scopes=AUTH_SCOPES) ): with sleuth.switch( 'googleapiclient.http.HttpRequest.execute', lambda x: True ) as mock_fn: kinds = ['backup_mockuser'] backup_datastore(kinds=kinds) self.assertTrue(mock_fn.called)
def test_sandbox_can_be_specified(self): with sleuth.switch("django.core.management.execute_from_command_line", lambda *args, **kwargs: None) as django_execute_mock, \ sleuth.switch("djangae.sandbox.activate", test_context_manager) as activate_sandbox_mock: # test default sandbox is used if no sandbox argument execute_from_command_line([ 'manage.py', 'arg1', 'arg2', ]) self.assertEqual(1, activate_sandbox_mock.call_count) self.assertEqual('local', activate_sandbox_mock.calls[0].args[0]) self.assertEqual(1, django_execute_mock.call_count) self.assertEqual(([ 'manage.py', 'arg1', 'arg2', ], ), django_execute_mock.calls[0].args) # test that sandbox argument is used when given execute_from_command_line([ 'manage.py', '--sandbox=test', 'arg1', 'arg2', ]) self.assertEqual(2, activate_sandbox_mock.call_count) self.assertEqual('test', activate_sandbox_mock.calls[1].args[0]) self.assertEqual(2, django_execute_mock.call_count) self.assertEqual(([ 'manage.py', 'arg1', 'arg2', ], ), django_execute_mock.calls[1].args) # test that sandbox argument can be in any position execute_from_command_line([ 'manage.py', 'arg1', '--sandbox=test', 'arg2', ]) self.assertEqual(3, activate_sandbox_mock.call_count) self.assertEqual('test', activate_sandbox_mock.calls[2].args[0]) self.assertEqual(3, django_execute_mock.call_count) self.assertEqual(([ 'manage.py', 'arg1', 'arg2', ], ), django_execute_mock.calls[2].args)
def test_arguments_are_passed_through_correctly(self): with sleuth.switch("django.core.management.execute_from_command_line", lambda *args, **kwargs: None) as django_execute_mock, \ sleuth.switch("djangae.sandbox.activate", test_context_manager): execute_from_command_line([ 'manage.py', 'arg1', 'arg2', 'arg3', ]) self.assertEqual(1, django_execute_mock.call_count) self.assertEqual(([ 'manage.py', 'arg1', 'arg2', 'arg3', ], ), django_execute_mock.calls[0].args)
def test_switch_to_same_account(self): gcu = 'djangae.contrib.gauth.middleware.users.get_current_user' final_destination = '/death/' switch_accounts_url = get_switch_accounts_url(next=final_destination) any_url = '/_ah/warmup' jekyll = users.User(email='*****@*****.**', _user_id='1') with sleuth.switch(gcu, lambda: jekyll): response = self.client.get(any_url) # Check that the user is logged in expected_user_query = GaeDatastoreUser.objects.filter(username=jekyll.user_id()) self.assertEqual(len(expected_user_query), 1) self.assertEqual(int(self.client.session['_auth_user_id']), expected_user_query[0].pk) # Call switch_accounts view, which should give a redirect to login url response = self.client.get(switch_accounts_url, follow=False) self.assertEqual(response.status_code, 302) self.assertEqual(response['location'], users.create_login_url(switch_accounts_url)) # Assume the user is signed in to one account, so it should redirect to logout url response = self.client.get(switch_accounts_url) self.assertEqual(response.status_code, 302) self.assertEqual( response['location'], users.create_logout_url(users.create_login_url(switch_accounts_url)) ) # Now the user decides against switching accounts and comes back with the same account response = self.client.get(switch_accounts_url) redirect_path = urlparse(response['location']).path self.assertEqual(redirect_path, final_destination) expected_user_query = GaeDatastoreUser.objects.filter(username=jekyll.user_id()) self.assertEqual(len(expected_user_query), 1) self.assertEqual(int(self.client.session['_auth_user_id']), expected_user_query[0].pk)
def test_get_next_available_port(self): url = "127.0.0.1" port = 8081 self.assertEquals(8081, get_next_available_port(url, port)) with sleuth.switch("djangae.utils.port_is_open", lambda *args, **kwargs: False if args[1] < 8085 else True): self.assertEquals(8085, get_next_available_port(url, port))
def test_user_creation_race_condition(self): """ If a user double clicks a 'login' button or something, causing 2 threads to be authenticating the same user at the same time, ensure it doesn't die. """ email = "*****@*****.**" user_id = "111111111100000000001" original_user_get = get_user_model().objects.get def crazy_user_get_patch(*args, **kwargs): """ Patch for User.objects.get which simulates another thread creating the same user immedidately after this is called (by doing it as part of this function). """ User = get_user_model() try: return original_user_get(*args, **kwargs) # We patched .get() except User.DoesNotExist: # This is horrible, but... the backend first tries get() by username and then tries # get() by email, and we only want to create our user after that second call if kwargs.keys() != ['username']: User.objects.create_user(username=user_id, email=email) raise backend = AppEngineUserAPIBackend() google_user = users.User(email, _user_id=user_id) user_class_path = "djangae.contrib.gauth.datastore.models.GaeDatastoreUser.objects.get" with sleuth.switch(user_class_path, crazy_user_get_patch): backend.authenticate(google_user)
def test_switch_accounts(self): gcu = 'djangae.contrib.gauth.middleware.users.get_current_user' final_destination = '/death/' # there's no escaping it switch_accounts_url = get_switch_accounts_url(next=final_destination) any_url = '/_ah/warmup' jekyll = users.User(email='*****@*****.**', _user_id='1') hyde = users.User(email='*****@*****.**', _user_id='2') # we start our scenario with the user logged in with sleuth.switch(gcu, lambda: jekyll): response = self.client.get(any_url) # Check that the user is logged in expected_user_query = GaeDatastoreUser.objects.filter( username=jekyll.user_id()) self.assertEqual(len(expected_user_query), 1) self.assertEqual(int(self.client._session()['_auth_user_id']), expected_user_query[0].pk) # Now call the switch_accounts view, which should give us a redirect to the login page response = self.client.get(switch_accounts_url, follow=False) self.assertEqual(response.status_code, 302) self.assertEqual(response['location'], users.create_login_url(switch_accounts_url)) # In tests, we don't have dev_appserver fired up, so we can't actually call the login # URL, but let's suppose that the user wasn't logged into multiple accounts at once # and so the login page redirected us straight back to the switch_accounts view. # It should detect this, and should now redirect us to the log*out* URL with a # destination of the log*in* URL response = self.client.get(switch_accounts_url) self.assertEqual(response.status_code, 302) self.assertEqual( response['location'], users.create_logout_url( users.create_login_url(switch_accounts_url))) # And now we have to emulate the scenario that we have now logged in with a different # account, so re-mock that with sleuth.switch(gcu, lambda: hyde): # Now that we're logged in as a different user, we expect request.user to get set to # the equivalent Django user and to be redirected to our final destination response = self.client.get(switch_accounts_url) redirect_path = urlparse( response['location']).path # it has the host name as well self.assertEqual(redirect_path, final_destination) expected_user_query = GaeDatastoreUser.objects.filter( username=hyde.user_id()) self.assertEqual(len(expected_user_query), 1) self.assertEqual(int(self.client._session()['_auth_user_id']), expected_user_query[0].pk)
def test_account_switch(self): user1 = users.User('*****@*****.**', _user_id='111111111100000000001') user2 = users.User('*****@*****.**', _user_id='222222222200000000002') request = HttpRequest() SessionMiddleware().process_request(request) # Make the damn sessions work middleware = AuthenticationMiddleware() with sleuth.switch('djangae.contrib.gauth.middleware.users.get_current_user', lambda: user1): middleware.process_request(request) self.assertEqual(user1.user_id(), request.user.username) with sleuth.switch('djangae.contrib.gauth.middleware.users.get_current_user', lambda: user2): middleware.process_request(request) self.assertEqual(user2.user_id(), request.user.username)
def test_get_next_available_port(self): url = "127.0.0.1" port = 8091 self.assertEquals(8091, get_next_available_port(url, port)) with sleuth.switch( "djangae.utils.port_is_open", lambda *args, **kwargs: False if args[1] < 8095 else True): self.assertEquals(8095, get_next_available_port(url, port))
def test_task_queue_name(self): # when not in task self.assertIsNone(task_queue_name()) os.environ["HTTP_X_APPENGINE_QUEUENAME"] = "demo123" self.assertIsNone(task_queue_name()) del os.environ["HTTP_X_APPENGINE_QUEUENAME"] self.assertIsNone(task_queue_name()) # when in task, w/o queue set with sleuth.switch('djangae.environment.is_in_task', lambda: True): self.assertEqual(task_queue_name(), "default") # when in task, with queue set with sleuth.switch('djangae.environment.is_in_task', lambda: True): os.environ["HTTP_X_APPENGINE_QUEUENAME"] = "demo123" self.assertEqual(task_queue_name(), "demo123") del os.environ["HTTP_X_APPENGINE_QUEUENAME"] self.assertEqual(task_queue_name(), "default")
def test_account_switch(self): user1 = users.User('*****@*****.**', _user_id='111111111100000000001') user2 = users.User('*****@*****.**', _user_id='222222222200000000002') request = HttpRequest() SessionMiddleware().process_request(request) # Make the damn sessions work request.session[BACKEND_SESSION_KEY] = 'djangae.contrib.gauth.datastore.backends.AppEngineUserAPIBackend' middleware = AuthenticationMiddleware() with sleuth.switch('djangae.contrib.gauth.middleware.users.get_current_user', lambda: user1): middleware.process_request(request) self.assertEqual(user1.user_id(), request.user.username) with sleuth.switch('djangae.contrib.gauth.middleware.users.get_current_user', lambda: user2): middleware.process_request(request) self.assertEqual(user2.user_id(), request.user.username)
def test_account_switch(self): def _get_user_one(): return users.User('*****@*****.**', _user_id='111111111100000000001') def _get_user_two(): return users.User('*****@*****.**', _user_id='222222222200000000002') request = HttpRequest() SessionMiddleware().process_request(request) # Make the damn sessions work middleware = AuthenticationMiddleware() with sleuth.switch('djangae.contrib.gauth.middleware.users.get_current_user', _get_user_one): middleware.process_request(request) self.assertEqual(_get_user_one().user_id(), request.user.username) with sleuth.switch('djangae.contrib.gauth.middleware.users.get_current_user', _get_user_two): middleware.process_request(request) self.assertEqual(_get_user_two().user_id(), request.user.username)
def test_switch_accounts(self): gcu = 'djangae.contrib.gauth.middleware.users.get_current_user' final_destination = '/death/' # there's no escaping it switch_accounts_url = get_switch_accounts_url(next=final_destination) any_url = '/_ah/warmup' jekyll = users.User(email='*****@*****.**', _user_id='1') hyde = users.User(email='*****@*****.**', _user_id='2') # we start our scenario with the user logged in with sleuth.switch(gcu, lambda: jekyll): response = self.client.get(any_url) # Check that the user is logged in expected_user_query = GaeDatastoreUser.objects.filter(username=jekyll.user_id()) self.assertEqual(len(expected_user_query), 1) self.assertEqual(int(self.client._session()['_auth_user_id']), expected_user_query[0].pk) # Now call the switch_accounts view, which should give us a redirect to the login page response = self.client.get(switch_accounts_url, follow=False) self.assertEqual(response.status_code, 302) self.assertEqual(response['location'], users.create_login_url(switch_accounts_url)) # In tests, we don't have dev_appserver fired up, so we can't actually call the login # URL, but let's suppose that the user wasn't logged into multiple accounts at once # and so the login page redirected us straight back to the switch_accounts view. # It should detect this, and should now redirect us to the log*out* URL with a # destination of the log*in* URL response = self.client.get(switch_accounts_url) self.assertEqual(response.status_code, 302) self.assertEqual( response['location'], users.create_logout_url(users.create_login_url(switch_accounts_url)) ) # And now we have to emulate the scenario that we have now logged in with a different # account, so re-mock that with sleuth.switch(gcu, lambda: hyde): # Now that we're logged in as a different user, we expect request.user to get set to # the equivalent Django user and to be redirected to our final destination response = self.client.get(switch_accounts_url) redirect_path = urlparse(response['location']).path # it has the host name as well self.assertEqual(redirect_path, final_destination) expected_user_query = GaeDatastoreUser.objects.filter(username=hyde.user_id()) self.assertEqual(len(expected_user_query), 1) self.assertEqual(int(self.client._session()['_auth_user_id']), expected_user_query[0].pk)
def test_force_user_pre_creation(self): email = '*****@*****.**' user1 = users.User(email, _user_id='111111111100000000001') with sleuth.switch('djangae.contrib.gauth.middleware.users.get_current_user', lambda: user1): request = HttpRequest() SessionMiddleware().process_request(request) # Make the damn sessions work middleware = AuthenticationMiddleware() middleware.process_request(request) # We expect request.user to be AnonymousUser(), because there was no User object in the DB # and so with pre-creation required, authentication should have failed self.assertTrue(isinstance(request.user, AnonymousUser))
def test_gae_conversion(self): #A PK IN query should result in a single get by key with sleuth.switch("djangae.db.backends.appengine.commands.datastore.Get", lambda *args, **kwargs: []) as get_mock: list(TestUser.objects.filter(pk__in=[1, 2, 3])) #Force the query to run self.assertEqual(1, get_mock.call_count) with sleuth.switch("djangae.db.backends.appengine.commands.datastore.Query.Run", lambda *args, **kwargs: []) as query_mock: list(TestUser.objects.filter(username="******")) self.assertEqual(1, query_mock.call_count) with sleuth.switch("djangae.db.backends.appengine.commands.datastore.MultiQuery.Run", lambda *args, **kwargs: []) as query_mock: list(TestUser.objects.filter(username__in=["test", "cheese"])) self.assertEqual(1, query_mock.call_count) with sleuth.switch("djangae.db.backends.appengine.commands.datastore.Get", lambda *args, **kwargs: []) as get_mock: list(TestUser.objects.filter(pk=1)) self.assertEqual(1, get_mock.call_count) with sleuth.switch("djangae.db.backends.appengine.commands.datastore.MultiQuery.Run", lambda *args, **kwargs: []) as query_mock: list(TestUser.objects.exclude(username__startswith="test")) self.assertEqual(1, query_mock.call_count)
def test_cache_disabled_elements_removed(self): entity_data = {"field1": "Apple", "comb1": 1, "comb2": "Cherry"} original = CachingTestModel.objects.create(**entity_data) # add to cache original.refresh_from_db() with sleuth.switch("djangae.db.backends.appengine.caching.CACHE_ENABLED", False): with sleuth.watch( "djangae.db.backends.appengine.caching._remove_entities_from_memcache_by_key" ) as _remove_entities_from_memcache_by_key: original.delete() self.assertFalse(_remove_entities_from_memcache_by_key.called)
def test_force_user_pre_creation(self): User = get_user_model() self.assertEqual(User.objects.count(), 0) google_user = users.User('*****@*****.**', _user_id='111111111100000000001') backend = AppEngineUserAPIBackend() self.assertIsNone(backend.authenticate(google_user=google_user,)) self.assertEqual(User.objects.count(), 0) # superusers don't need pre-creation of User object. self.assertEqual(User.objects.count(), 0) with sleuth.switch('google.appengine.api.users.is_current_user_admin', lambda: True): user = backend.authenticate(google_user=google_user,) self.assertEqual(User.objects.count(), 1) self.assertEquals(User.objects.get(), user)
def test_models_using_the_same_table_only_listed_once(self): class ModelFoo(models.Model): class Meta: db_table = "foo" class ModelBar(models.Model): class Meta: db_table = "foo" def mock_get_app_models(**kwargs): return [ModelFoo, ModelBar] with sleuth.switch('django.apps.apps.get_models', mock_get_app_models): valid_models = _get_valid_export_kinds() self.assertEquals(['foo'], valid_models)
def test_sandbox_can_be_specified(self): with sleuth.switch("django.core.management.execute_from_command_line", lambda *args, **kwargs: None) as django_execute_mock, \ sleuth.switch("djangae.sandbox.activate", test_context_manager) as activate_sandbox_mock: # test default sandbox is used if no sandbox argument execute_from_command_line(['manage.py', 'arg1', 'arg2',]) self.assertEqual(1, activate_sandbox_mock.call_count) self.assertEqual('local', activate_sandbox_mock.calls[0].args[0]) self.assertEqual(1, django_execute_mock.call_count) self.assertEqual((['manage.py', 'arg1', 'arg2',],), django_execute_mock.calls[0].args) # test that sandbox argument is used when given execute_from_command_line(['manage.py', '--sandbox=test', 'arg1', 'arg2',]) self.assertEqual(2, activate_sandbox_mock.call_count) self.assertEqual('test', activate_sandbox_mock.calls[1].args[0]) self.assertEqual(2, django_execute_mock.call_count) self.assertEqual((['manage.py', 'arg1', 'arg2',],), django_execute_mock.calls[1].args) # test that sandbox argument can be in any position execute_from_command_line(['manage.py', 'arg1', '--sandbox=test', 'arg2',]) self.assertEqual(3, activate_sandbox_mock.call_count) self.assertEqual('test', activate_sandbox_mock.calls[2].args[0]) self.assertEqual(3, django_execute_mock.call_count) self.assertEqual((['manage.py', 'arg1', 'arg2',],), django_execute_mock.calls[2].args)
def test_cache_disabled_elements_not_added(self): entity_data = {"field1": "Apple", "comb1": 1, "comb2": "Cherry"} original = CachingTestModel.objects.create(**entity_data) # add to cache original.refresh_from_db() with sleuth.switch("djangae.db.backends.appengine.caching.CACHE_ENABLED", False): with sleuth.watch( "djangae.db.backends.appengine.caching._add_entity_to_memcache" ) as _add_entity_to_memcache: instance = CachingTestModel.objects.get(pk=original.pk) self.assertFalse(_add_entity_to_memcache.called)
def test_cache_disabled_elements_removed(self): entity_data = {"field1": "Apple", "comb1": 1, "comb2": "Cherry"} original = CachingTestModel.objects.create(**entity_data) # add to cache original.refresh_from_db() with sleuth.switch( "djangae.db.backends.appengine.caching.CACHE_ENABLED", False): with sleuth.watch( "djangae.db.backends.appengine.caching._remove_entities_from_memcache_by_key" ) as _remove_entities_from_memcache_by_key: original.delete() self.assertFalse(_remove_entities_from_memcache_by_key.called)
def test_cache_disabled_elements_not_added(self): entity_data = {"field1": "Apple", "comb1": 1, "comb2": "Cherry"} original = CachingTestModel.objects.create(**entity_data) # add to cache original.refresh_from_db() with sleuth.switch( "djangae.db.backends.appengine.caching.CACHE_ENABLED", False): with sleuth.watch( "djangae.db.backends.appengine.caching._add_entity_to_memcache" ) as _add_entity_to_memcache: instance = CachingTestModel.objects.get(pk=original.pk) self.assertFalse(_add_entity_to_memcache.called)
def test_unicode_with_active_language(self): """ If there's a currently-active language, unicode should return the translated text. """ def mock_get_translation(text, hint, language_code): if language_code == "de": return {"singular": "translated", "o": "translated"} return {"singular": self.text} translation.activate("de") with sleuth.switch( "fluent.fields.trans.TRANSLATION_CACHE.get_translation", mock_get_translation ): obj = TranslatableContent(text=u'\xc5ukasz') result = unicode(obj) self.assertEqual(result, u'translated') self.assertIsInstance(result, unicode)
def test_outermost_transaction_applies_all_contexts_on_commit(self): entity_data = {"field1": "Apple", "comb1": 1, "comb2": "Cherry"} with transaction.atomic(): with transaction.atomic(independent=True): instance = CachingTestModel.objects.create(**entity_data) # At this point the instance should be unretrievable, even though we just created it try: CachingTestModel.objects.get(pk=instance.pk) self.fail("Unexpectedly was able to retrieve instance") except CachingTestModel.DoesNotExist: pass # Should now exist in the cache with sleuth.switch( "google.appengine.api.datastore.Get") as datastore_get: CachingTestModel.objects.get(pk=instance.pk) self.assertFalse(datastore_get.called)
def test_middleware_resaves_email(self): # Create user with uppercased email email = '*****@*****.**' google_user = users.User(email, _user_id='111111111100000000001') backend = AppEngineUserAPIBackend() user = backend.authenticate(google_user=google_user,) # Normalize_email should save a user with lowercase email self.assertEqual(user.email, email.lower()) # Run AuthenticationMiddleware, if email are mismatched with sleuth.switch('djangae.contrib.gauth.middleware.users.get_current_user', lambda: google_user): request = HttpRequest() SessionMiddleware().process_request(request) # Make the damn sessions work middleware = AuthenticationMiddleware() middleware.process_request(request) # Middleware should resave to uppercased email, keeping user the same self.assertEqual(request.user.email, email) self.assertEqual(request.user.pk, user.pk)
def test_deferred_builtin_on(self): # Read and parse app.yaml app_yaml_path = os.path.join(get_application_root(), "app.yaml") with open(app_yaml_path, 'r') as f: app_yaml = yaml.load(f.read()) builtins = app_yaml.get('builtins', []) # Switch on deferred builtin builtins.append({'deferred': 'on'}) app_yaml['builtins'] = builtins # Write to temporary app.yaml temp_app_yaml_dir = tempfile.mkdtemp() temp_app_yaml_path = os.path.join(temp_app_yaml_dir, "app.yaml") temp_app_yaml = file(temp_app_yaml_path, 'w') yaml.dump(app_yaml, temp_app_yaml) with sleuth.switch('djangae.checks.get_application_root', lambda : temp_app_yaml_dir) as mock_app_root: warnings = check_deferred_builtin() self.assertEqual(len(warnings), 1) self.assertEqual(warnings[0].id, 'djangae.W001')
def test_deferred_builtin_on(self): # Read and parse app.yaml app_yaml_path = os.path.join(get_application_root(), "app.yaml") with open(app_yaml_path, 'r') as f: app_yaml = yaml.load(f.read()) builtins = app_yaml.get('builtins', []) # Switch on deferred builtin builtins.append({'deferred': 'on'}) app_yaml['builtins'] = builtins # Write to temporary app.yaml temp_app_yaml_dir = tempfile.mkdtemp() temp_app_yaml_path = os.path.join(temp_app_yaml_dir, "app.yaml") temp_app_yaml = file(temp_app_yaml_path, 'w') yaml.dump(app_yaml, temp_app_yaml) with sleuth.switch('djangae.checks.get_application_root', lambda : temp_app_yaml_dir) as mock_app_root: warnings = checks.check_deferred_builtin() self.assertEqual(len(warnings), 1) self.assertEqual(warnings[0].id, 'djangae.W001')
def test_outermost_transaction_applies_all_contexts_on_commit(self): entity_data = { "field1": "Apple", "comb1": 1, "comb2": "Cherry" } with transaction.atomic(): with transaction.atomic(independent=True): instance = CachingTestModel.objects.create(**entity_data) # At this point the instance should be unretrievable, even though we just created it try: CachingTestModel.objects.get(pk=instance.pk) self.fail("Unexpectedly was able to retrieve instance") except CachingTestModel.DoesNotExist: pass # Should now exist in the cache with sleuth.switch("google.appengine.api.datastore.Get") as datastore_get: CachingTestModel.objects.get(pk=instance.pk) self.assertFalse(datastore_get.called)
def test_app_engine_sdk_version_check_unsupported(self): with sleuth.switch('djangae.checks._VersionList', lambda x: [100, 0, 0]): errors = checks.check_app_engine_sdk_version() self.assertEqual(len(errors), 1) self.assertEqual(errors[0].id, 'djangae.W002')
def test_arguments_are_passed_through_correctly(self): with sleuth.switch("django.core.management.execute_from_command_line", lambda *args, **kwargs: None) as django_execute_mock, \ sleuth.switch("djangae.sandbox.activate", test_context_manager): execute_from_command_line(['manage.py', 'arg1', 'arg2', 'arg3',]) self.assertEqual(1, django_execute_mock.call_count) self.assertEqual((['manage.py', 'arg1', 'arg2', 'arg3',],), django_execute_mock.calls[0].args)