我们从Python开源项目中,提取了以下48个代码示例,用于说明如何使用pyramid.testing.DummyRequest()。
def test_apply_schema_edits(self): from eea.corpus.processing import pipeline_registry as pr from eea.corpus.views import CreateCorpusView LimitSchema = pr['eea_corpus_processing_limit_process'].schema HTMLSchema = pr['eea_corpus_processing_html_process'].schema PrepSchema = pr['eea_corpus_processing_preprocess_process'].schema schemas = [ LimitSchema(name='1st'), HTMLSchema(name='2st'), PrepSchema(name='3st'), ] req = testing.DummyRequest() view = CreateCorpusView(req) res = view._apply_schema_edits(schemas, ['move_up_1st_success']) assert [x.name for x in res] == [ '1st', '2st', '3st' ] # TODO: finish test
def test_route_items(): """Routed items appear in the sitemap.""" with pyramid.testing.testConfig() as config: request = DummyRequest() config.add_route('bar', '/bar/{id}') s = sitemap.Sitemap() s.add_item(sitemap.RouteItem("bar", id=1, lastmod="2015-01-01")) s.add_item(sitemap.RouteItem("bar", id=2, priority="1.0")) s.add_item(sitemap.RouteItem("bar", id=3, changefreq="never")) data = s.render(None, request) items = list(data["urlset"]) assert len(items) == 3 assert items[0].location(request) == "http://example.com/bar/1" assert items[0].lastmod(request) == "2015-01-01" assert items[1].location(request) == "http://example.com/bar/2" assert items[1].priority(request) == "1.0" assert items[2].location(request) == "http://example.com/bar/3" assert items[2].changefreq(request) == "never"
def test_get_public_user_data(self): self.config.testing_securitypolicy(userid='Tobias', permissive=True) # more tests for get_public_user_data are in test_handler_opinion from dbas.views import get_public_user_data as ajax request = testing.DummyRequest(params={ 'lang': 'en', 'uids': json.dumps([2, 3]), 'is_argument': 'true', 'is_attitude': 'true', 'is_reaction': 'true', 'is_position': 'true', 'is_supporti': 'true', }, matchdict={}) response = ajax(request) self.assertIsNotNone(response) self.assertTrue(len(response['error']) != 0)
def test_page(self): from dbas.views import discussion_reaction as d len_db_seen_s1 = len(DBDiscussionSession.query(SeenStatement).all()) len_db_votes_s1 = len(DBDiscussionSession.query(ClickedStatement).all()) len_db_seen_a1 = len(DBDiscussionSession.query(SeenArgument).all()) len_db_votes_a1 = len(DBDiscussionSession.query(ClickedArgument).all()) request = testing.DummyRequest(matchdict={ 'slug': 'cat-or-dog', 'arg_id_user': 2, 'mode': 'undermine', 'arg_id_sys': 16, }) response = d(request) verify_dictionary_of_view(self, response) len_db_seen_s2 = len(DBDiscussionSession.query(SeenStatement).all()) len_db_votes_s2 = len(DBDiscussionSession.query(ClickedStatement).all()) len_db_seen_a2 = len(DBDiscussionSession.query(SeenArgument).all()) len_db_votes_a2 = len(DBDiscussionSession.query(ClickedArgument).all()) self.assertEqual(len_db_seen_s1, len_db_seen_s2) # no more cause we are not logged in self.assertEqual(len_db_votes_s1, len_db_votes_s2) self.assertEqual(len_db_seen_a1, len_db_seen_a2) self.assertEqual(len_db_votes_a1, len_db_votes_a2)
def test_page_failure(self): from dbas.views import main_settings as d request = testing.DummyRequest(params={ 'form.passwordchange.submitted': '', 'passwordold': 'tobia', 'password': 'tobias', 'passwordconfirm': 'tobias' }) response = d(request) verify_dictionary_of_view(self, response) # check settings self.assertTrue(len(response['settings']['passwordold']) != 0) self.assertTrue(len(response['settings']['password']) != 0) self.assertTrue(len(response['settings']['passwordconfirm']) != 0)
def test_page_success(self): from dbas.views import main_settings as d db_user = DBDiscussionSession.query(User).filter_by(nickname='Tobias').first() db_user.password = get_hashed_password('tobias') transaction.commit() request = testing.DummyRequest(params={ 'form.passwordchange.submitted': '', 'passwordold': 'tobias', 'password': 'tobiass', 'passwordconfirm': 'tobiass' }) response = d(request) verify_dictionary_of_view(self, response) # check settings self.assertTrue(len(response['settings']['passwordold']) == 0) self.assertTrue(len(response['settings']['password']) == 0) self.assertTrue(len(response['settings']['passwordconfirm']) == 0) db_user = DBDiscussionSession.query(User).filter_by(nickname='Tobias').first() db_user.password = get_hashed_password('tobias') transaction.commit()
def test_flag_argument_or_statement_twice(self): self.config.testing_securitypolicy(userid='Tobias', permissive=True) from dbas.views import flag_argument_or_statement as ajax request = testing.DummyRequest(params={ 'uid': 2, 'reason': 'offtopic', 'is_argument': 'false', }, matchdict={}) response = json.loads(ajax(request)) self.assertIsNotNone(response) self.assertTrue(len(response['error']) == 0) self.assertTrue(len(response['success']) == 0) self.assertTrue(len(response['info']) != 0) DBDiscussionSession.query(ReviewDelete).filter_by(statement_uid=2).delete() DBDiscussionSession.query(ReviewOptimization).filter_by(statement_uid=2).delete() transaction.commit()
def test_merge_statement(self): self.config.testing_securitypolicy(userid='Tobias', permissive=True) from dbas.views import split_or_merge_statement as ajax request = testing.DummyRequest(params={ 'pgroup_uid': 20, 'key': 'merge', 'text_values': json.dumps(['it is based on the cats race', 'not every cat is capricious']) }, matchdict={}) # oem of 20 is: 'the fact, that cats are capricious, is based on the cats race' db_review1 = len(DBDiscussionSession.query(ReviewMerge).all()) db_values1 = len(DBDiscussionSession.query(ReviewMergeValues).all()) response = json.loads(ajax(request)) db_review2 = len(DBDiscussionSession.query(ReviewMerge).all()) db_values2 = len(DBDiscussionSession.query(ReviewMergeValues).all()) self.assertEqual(len(response['error']), 0) self.assertEqual(len(response['info']), 0) self.assertNotEqual(len(response['success']), 0) self.assertEqual(db_review1 + 1, db_review2) self.assertEqual(db_values1 + 2, db_values2) tmp = DBDiscussionSession.query(ReviewMerge).filter_by(premisesgroup_uid=20).first() DBDiscussionSession.query(ReviewMergeValues).filter_by(review_uid=tmp.uid).delete() DBDiscussionSession.query(ReviewMerge).filter_by(premisesgroup_uid=20).delete() DBDiscussionSession.flush() transaction.commit()
def test_split_premisegroup(self): self.config.testing_securitypolicy(userid='Tobias', permissive=True) from dbas.views import split_or_merge_premisegroup as ajax request = testing.DummyRequest(params={ 'pgroup_uid': 21, 'key': 'split', }, matchdict={}) db_review1 = len(DBDiscussionSession.query(ReviewSplit).all()) db_values1 = len(DBDiscussionSession.query(ReviewSplitValues).all()) response = json.loads(ajax(request)) db_review2 = len(DBDiscussionSession.query(ReviewSplit).all()) db_values2 = len(DBDiscussionSession.query(ReviewSplitValues).all()) self.assertEqual(len(response['error']), 0) self.assertEqual(len(response['info']), 0) self.assertNotEqual(len(response['success']), 0) self.assertEqual(db_review1 + 1, db_review2) self.assertEqual(db_values1, db_values2) tmp = DBDiscussionSession.query(ReviewSplit).filter_by(premisesgroup_uid=21).first() DBDiscussionSession.query(ReviewSplitValues).filter_by(review_uid=tmp.uid).delete() DBDiscussionSession.query(LastReviewerSplit).filter_by(review_uid=tmp.uid).delete() DBDiscussionSession.query(PremiseGroupSplitted).filter_by(review_uid=tmp.uid).delete() DBDiscussionSession.query(ReviewSplit).filter_by(premisesgroup_uid=21).delete() DBDiscussionSession.flush() transaction.commit()
def test_merge_premisegroup(self): self.config.testing_securitypolicy(userid='Tobias', permissive=True) from dbas.views import split_or_merge_premisegroup as ajax request = testing.DummyRequest(params={ 'pgroup_uid': 21, 'key': 'merge', }, matchdict={}) db_review1 = len(DBDiscussionSession.query(ReviewMerge).all()) db_values1 = len(DBDiscussionSession.query(ReviewMergeValues).all()) response = json.loads(ajax(request)) db_review2 = len(DBDiscussionSession.query(ReviewMerge).all()) db_values2 = len(DBDiscussionSession.query(ReviewMergeValues).all()) self.assertEqual(len(response['error']), 0) self.assertEqual(len(response['info']), 0) self.assertNotEqual(len(response['success']), 0) self.assertEqual(db_review1 + 1, db_review2) self.assertEqual(db_values1, db_values2) tmp = DBDiscussionSession.query(ReviewMerge).filter_by(premisesgroup_uid=21).first() DBDiscussionSession.query(ReviewMergeValues).filter_by(review_uid=tmp.uid).delete() DBDiscussionSession.query(ReviewMerge).filter_by(premisesgroup_uid=21).delete() DBDiscussionSession.flush() transaction.commit()
def test_send_notification(self): self.config.testing_securitypolicy(userid='Tobias', permissive=True) from dbas.views import send_some_notification as ajax db_len1 = len(DBDiscussionSession.query(Message).filter(and_(Message.topic == 'Some text for a message', Message.content == 'Some text for a message')).all()) request = testing.DummyRequest(params={ 'recipient': 'Christian', 'title': 'Some text for a message', 'text': 'Some text for a message', }, matchdict={}) response = ajax(request) db_len2 = len(DBDiscussionSession.query(Message).filter(and_(Message.topic == 'Some text for a message', Message.content == 'Some text for a message')).all()) self.assertIsNotNone(response) self.assertTrue(len(response['error']) == 0) self.assertTrue(db_len1 != db_len2) DBDiscussionSession.query(Message).filter(and_(Message.topic == 'Some text for a message', Message.content == 'Some text for a message')).delete() transaction.commit()
def test_set_user_setting_mail(self): from dbas.views import set_user_settings as ajax request = testing.DummyRequest(params={'ui_locales': 'en'}) response = ajax(request) self.assertTrue(len(response['error']) > 0) self.config.testing_securitypolicy(userid='Tobias', permissive=True) request = testing.DummyRequest(params={'service': 'mail', 'settings_value': False}) response = ajax(request) self.assertIn('error', response) self.assertIn('public_nick', response) self.assertIn('public_page_url', response) self.assertIn('gravatar_url', response) self.assertTrue(response['error'] == '') self.assertTrue(response['public_nick'] != '') self.assertTrue(response['public_page_url'] != '') self.assertTrue(response['gravatar_url'] != '')
def test_set_user_setting_notification(self): from dbas.views import set_user_settings as ajax request = testing.DummyRequest(params={'ui_locales': 'en'}) response = ajax(request) self.assertTrue(len(response['error']) > 0) self.config.testing_securitypolicy(userid='Tobias', permissive=True) request = testing.DummyRequest(params={'service': 'notification', 'settings_value': True}) response = ajax(request) self.assertIn('error', response) self.assertIn('public_nick', response) self.assertIn('public_page_url', response) self.assertIn('gravatar_url', response) self.assertTrue(response['error'] == '') self.assertTrue(response['public_nick'] != '') self.assertTrue(response['public_page_url'] != '') self.assertTrue(response['gravatar_url'] != '')
def test_set_user_setting_nick(self): from dbas.views import set_user_settings as ajax request = testing.DummyRequest(params={'ui_locales': 'en'}) response = ajax(request) self.assertTrue(len(response['error']) > 0) self.config.testing_securitypolicy(userid='Tobias', permissive=True) request = testing.DummyRequest(params={'service': 'public_nick', 'settings_value': False}) response = ajax(request) self.assertIn('error', response) self.assertIn('public_nick', response) self.assertIn('public_page_url', response) self.assertIn('gravatar_url', response) self.assertTrue(response['error'] == '') self.assertTrue(response['public_nick'] != '') self.assertTrue(response['public_page_url'] != '') self.assertTrue(response['gravatar_url'] != '')
def test_set_user_setting_no_service(self): from dbas.views import set_user_settings as ajax request = testing.DummyRequest(params={'ui_locales': 'en'}) response = ajax(request) self.assertTrue(len(response['error']) > 0) self.config.testing_securitypolicy(userid='Tobias', permissive=True) request = testing.DummyRequest(params={'service': 'oha', 'settings_value': False}) response = ajax(request) self.assertIn('error', response) self.assertIn('public_nick', response) self.assertIn('public_page_url', response) self.assertIn('gravatar_url', response) self.assertTrue(response['error'] != '') self.assertTrue(response['public_nick'] != '') self.assertTrue(response['public_page_url'] != '') self.assertTrue(response['gravatar_url'] != '')
def test_set_new_start_statement_reputation(self): self.config.testing_securitypolicy(userid='Björn', permissive=True) from dbas.views import set_new_start_statement as ajax request = testing.DummyRequest(params={'statement': 'New statement for an issue'}, matchdict={}) response = ajax(request) self.assertIsNotNone(response) self.assertTrue(len(response['error']) == 0) self.assertTrue(len(response['url']) != 0) self.assertTrue(len(response['statement_uids']) != 0) for uid in response['statement_uids']: DBDiscussionSession.query(TextVersion).filter_by(statement_uid=uid).delete() DBDiscussionSession.query(MarkedStatement).filter_by(statement_uid=uid).delete() DBDiscussionSession.query(SeenStatement).filter_by(statement_uid=uid).delete() DBDiscussionSession.query(Statement).filter_by(uid=uid).delete() db_user = DBDiscussionSession.query(User).filter_by(nickname='Björn').first() DBDiscussionSession.query(ReputationHistory).filter_by(reputator_uid=db_user.uid).delete() transaction.commit()
def test_set_new_start_premise_twice(self): self.config.testing_securitypolicy(userid='Björn', permissive=True) from dbas.views import set_new_start_premise as ajax db_arg1 = len(DBDiscussionSession.query(Argument).filter_by(conclusion_uid=2).all()) len_db_reputation1 = len(DBDiscussionSession.query(ReputationHistory).all()) request = testing.DummyRequest(params={ 'premisegroups': json.dumps(['this is my first premisegroup']), 'conclusion_id': 2, 'issue': 2, 'supportive': 'true' }, matchdict={}) response = ajax(request) transaction.commit() db_arg2 = len(DBDiscussionSession.query(Argument).filter_by(conclusion_uid=2).all()) len_db_reputation2 = len(DBDiscussionSession.query(ReputationHistory).all()) self.assertIsNotNone(response) self.assertEquals(db_arg1 + 1, db_arg2) self.assertEquals(len_db_reputation1 + 1, len_db_reputation2) self.delete_last_argument_by_conclusion_uid(2) db_user = DBDiscussionSession.query(User).filter_by(nickname='Björn').first() DBDiscussionSession.query(ReputationHistory).filter_by(reputator_uid=db_user.uid).delete() transaction.commit()
def test_set_new_premises_for_argument(self): self.config.testing_securitypolicy(userid='Tobias', permissive=True) from dbas.views import set_new_premises_for_argument as ajax db_arg1 = len(DBDiscussionSession.query(Argument).filter_by(uid=2).all()) db_pgroups1 = len(DBDiscussionSession.query(PremiseGroup).all()) request = testing.DummyRequest(params={ 'premisegroups': json.dumps(['some new reason for an argument']), 'arg_uid': 2, 'attack_type': 'support', 'issue': 2 }, matchdict={}) response = ajax(request) db_arg2 = len(DBDiscussionSession.query(Argument).filter_by(uid=2).all()) db_pgroups2 = len(DBDiscussionSession.query(PremiseGroup).all()) self.assertIsNotNone(response) self.assertTrue(len(response['error']) == 0) self.assertTrue(db_arg1 + 1, db_arg2) self.assertTrue(db_pgroups1 + 1, db_pgroups2) self.delete_last_argument_by_conclusion_uid(2)
def test_set_new_issue(self): self.config.testing_securitypolicy(userid='Tobias', permissive=True) from dbas.views import set_new_issue as ajax request = testing.DummyRequest(params={ 'info': 'Some new info', 'long_info': 'Some new long info', 'title': 'Some new title', 'lang': 'en', 'is_public': 'False', 'is_read_only': 'False' }, matchdict={}) response = ajax(request) self.assertIsNotNone(response) self.assertTrue(len(response['error']) == 0) self.assertEqual(len(DBDiscussionSession.query(Issue).filter_by(title='Some new title').all()), 1) DBDiscussionSession.query(Issue).filter_by(title='Some new title').delete() transaction.commit()
def test_page_logged_in(self): from dbas.views import discussion_init as d self.config.testing_securitypolicy(userid='Tobias', permissive=True) # check count of seen by statements db_user = DBDiscussionSession.query(User).filter_by(nickname='Tobias').first() len_db_seen1 = len(DBDiscussionSession.query(SeenStatement).filter_by(user_uid=db_user.uid).all()) request = testing.DummyRequest() response = d(request) verify_dictionary_of_view(self, response) # elements, which were seen self.assertIn('elements', response['items']) el_count = len(response['items']['elements']) - 1 # -1 for login / add len_db_seen2 = len(DBDiscussionSession.query(SeenStatement).filter_by(user_uid=db_user.uid).all()) self.assertEqual(len_db_seen1 + el_count, len_db_seen2) transaction.commit() # normally pyramid_tm does this
def test_page_logged_in_again(self): from dbas.views import discussion_init as d self.config.testing_securitypolicy(userid='Tobias', permissive=True) # check count of seen by statements db_user = DBDiscussionSession.query(User).filter_by(nickname='Tobias').first() len_db_seen1 = len(DBDiscussionSession.query(SeenStatement).filter_by(user_uid=db_user.uid).all()) request = testing.DummyRequest() response = d(request) verify_dictionary_of_view(self, response) # elements, which were seen are now equals the first, cause we have seen them already len_db_seen2 = len(DBDiscussionSession.query(SeenStatement).filter_by(user_uid=db_user.uid).all()) self.assertEqual(len_db_seen1, len_db_seen2) # remove seen statements db_user = DBDiscussionSession.query(User).filter_by(nickname='Tobias').first() DBDiscussionSession.query(SeenStatement).filter_by(user_uid=db_user.uid).delete() transaction.commit()
def test_passing_view(self): from .views import my_view request = testing.DummyRequest() info = my_view(request) self.assertEqual(info['one'].name, 'one') self.assertEqual(info['project'], 'fantasydota')
def test_failing_view(self): from .views import my_view request = testing.DummyRequest() info = my_view(request) self.assertEqual(info.status_int, 500)
def test_passing_view(self): from .views import my_view request = testing.DummyRequest() info = my_view(request) self.assertEqual(info['one'].name, 'one') self.assertEqual(info['project'], 'source')
def test_my_view(self): from .views import my_view request = testing.DummyRequest() info = my_view(request) self.assertEqual(info['project'], '{{ cookiecutter.project_name }}')
def dummy_request(db_session): """Instantiate a fake HTTP Request, complete with a database session. This is a function-level fixture, so every new request will have a new database session. """ return testing.DummyRequest(dbsession=db_session)
def dummy_request(db_session): """Create a dummy request.""" from pyramid import testing req = testing.DummyRequest() req.dbsession = db_session return req
def home_response(): """Return a response from home page.""" from turingtweets.views.default import home_view request = testing.DummyRequest() response = home_view(request) return response # ============Test of POST request===============
def buildCmd(session, klass, params={}, username="test"): request = testing.DummyRequest() request.context = testing.DummyResource() md = MultiDict() for key, val in params.items(): md.add(key, val) request.params = NestedMultiDict(md) request.authed_user = models.getUserByName(session, username) cmd = klass(None, request, session=session) cmd.settings = {"mishmash.paths": "Music: test/music"} return cmd
def test_my_view(self): from .views import my_view request = testing.DummyRequest() info = my_view(request) self.assertEqual(info['project'], 'nflpool')
def test_action_map(self): request = testing.DummyRequest() response = self.viewset(request) expected = {'method': 'GET', 'action': 'list'} assert response.status_code == 200 assert response.body == expected
def setUp(self): self.dbsession = get_dbsession() self.list_viewset = UserViewSet.as_view({'get': 'list', 'post': 'create'}) self.detail_viewset = UserViewSet.as_view( {'get': 'retrieve', 'put': 'update', 'patch': 'partial_update', 'delete': 'destroy'}) self.request = testing.DummyRequest() self.request.dbsession = self.dbsession
def setUp(self): self.test_view = MyView.as_view(name='MyView') self.request = testing.DummyRequest()
def test_no_page_number(self): request = testing.DummyRequest() request.current_route_url = mock.Mock(side_effect=self.get_current_url) queryset = self.paginate_queryset(request) content = self.get_paginated_content(queryset) assert queryset == [1, 2, 3, 4, 5] assert content == { 'results': [1, 2, 3, 4, 5], 'previous': None, 'next': 'http://testserver/?page=2', 'count': 100 }
def test_second_page(self): request = testing.DummyRequest() request.params['page'] = 2 request.current_route_url = mock.Mock(side_effect=self.get_current_url) queryset = self.paginate_queryset(request) content = self.get_paginated_content(queryset) assert queryset == [6, 7, 8, 9, 10] assert content == { 'results': [6, 7, 8, 9, 10], 'previous': 'http://testserver/', 'next': 'http://testserver/?page=3', 'count': 100 }
def test_invalid_page(self): request = testing.DummyRequest() request.params['page'] = 'invalid' request.current_route_url = mock.Mock(side_effect=self.get_current_url) self.assertRaises(HTTPNotFound, self.paginate_queryset, request)
def test_no_page_number(self): request = testing.DummyRequest() request.current_route_url = mock.Mock(side_effect=self.get_current_url) queryset = self.paginate_queryset(request) content = self.get_paginated_content(queryset) assert queryset == [1] assert content == { 'results': [1, ], 'previous': None, 'next': None, 'count': 1 }
def test_invalid_page(self): request = testing.DummyRequest() request.params['page'] = 'invalid' request.current_route_url = mock.Mock(side_effect=self.get_current_url) with pytest.raises(HTTPNotFound): self.paginate_queryset(request)
def test_overridden_query_param(self): request = testing.DummyRequest() request.params['unit'] = 1 request.current_route_url = mock.Mock(side_effect=self.get_current_url) queryset = self.paginate_queryset(request) content = self.get_paginated_content(queryset) assert queryset == [1] assert content == { 'results': [1, ], 'previous': None, 'next': None, 'count': 1 }
def test_no_page_number(self): request = testing.DummyRequest() request.current_route_url = mock.Mock(side_effect=self.get_current_url) queryset = self.paginate_queryset(request) response = self.get_paginated_response(queryset) assert queryset == [1, 2, 3, 4, 5] assert response.json_body == [1, 2, 3, 4, 5] # todo, if renders are ever implemented this needs updated assert response.headers['Link'] == '<http://testserver/?page=2>; rel="next", <http://testserver/?page=1>; ' + \ 'rel="first", <http://testserver/?page=20>; rel="last"'
def test_last_page(self): request = testing.DummyRequest() request.params['page'] = 'last' request.current_route_url = mock.Mock(side_effect=self.get_current_url) queryset = self.paginate_queryset(request) response = self.get_paginated_response(queryset) assert queryset == [96, 97, 98, 99, 100] assert response.json_body == [96, 97, 98, 99, 100] # todo, if renders are ever implemented this needs updated assert response.headers['Link'] == '<http://testserver/?page=19>; rel="prev", <http://testserver/?page=1>; ' +\ 'rel="first", <http://testserver/?page=20>; rel="last"'
def setUp(self): self.request = testing.DummyRequest() self.request.dbsession = mock.Mock()
def setUp(self): self.request = testing.DummyRequest() self.request.dbsession = self.dbsession
def setUp(self): super(TestAPIResourceListing, self).setUp() self.config.include('cornice') self.config.scan('.views') self.request = testing.DummyRequest() self.request.registry.db = Mock() self.request.registry.server_id = Mock() self.request.registry.couchdb_server = Mock() self.request.registry.update_after = True self.context = Mock()
def test_unauthenticated_userid_bearer(self): request = testing.DummyRequest() request.headers['Authorization'] = 'Bearer chrisr' policy = self._makeOne(None) self.assertEqual(policy.unauthenticated_userid(request), 'chrisr')
def test_my_view(self): from .views import my_view request = testing.DummyRequest() info = my_view(request) self.assertEqual(info['project'], 'consuming_services_apis')