def whitenoise_tween(request): whn = request.registry.whitenoise if whn.autorefresh: static_file = whn.find_file(request.path_info) else: static_file = whn.files.get(request.path_info) # We could not find a static file, so we'll just continue processing # this as normal. if static_file is None: return handler(request) request_headers = dict(kv for kv in request.environ.items() if kv[0].startswith("HTTP_")) if request.method not in {"GET", "HEAD"}: return HTTPMethodNotAllowed() else: path, headers = static_file.get_path_and_headers(request_headers) headers = MultiDict(headers) resp = FileResponse( path, request=request, content_type=headers.pop("Content-Type", None), content_encoding=headers.pop("Content-Encoding", None), ) resp.md5_etag() resp.headers.update(headers) return resp
def test_without_a_query(self, monkeypatch, db_request, page): params = MultiDict() if page is not None: params["page"] = page db_request.params = params es_query = pretend.stub() db_request.es = pretend.stub(query=lambda *a, **kw: es_query) page_obj = pretend.stub(page_count=(page or 1) + 10) page_cls = pretend.call_recorder(lambda *a, **kw: page_obj) monkeypatch.setattr(views, "ElasticsearchPage", page_cls) url_maker = pretend.stub() url_maker_factory = pretend.call_recorder(lambda request: url_maker) monkeypatch.setattr(views, "paginate_url_factory", url_maker_factory) assert search(db_request) == { "page": page_obj, "term": params.get("q", ''), "order": params.get("o", ''), "applied_filters": [], "available_filters": [], } assert page_cls.calls == [ pretend.call(es_query, url_maker=url_maker, page=page or 1), ] assert url_maker_factory.calls == [pretend.call(db_request)]
class Utility(object): def __init__(self): self.accept_headers = MultiDict() self.deserializers = {} def add_deserializer(self, content_type, callable): self.deserializers[content_type] = callable self.accept_headers.add('Accept', content_type) def deserialize_request_body(self, request): content_type = request.content_type deserialized = None request.response.headers.extend(self.accept_headers) if content_type in self.deserializers: try: deserialized = self.deserializers[content_type](request) except HTTPException as http_exc: http_exc.headers.extend(self.accept_headers) raise else: raise HTTPUnsupportedMediaType(content_type, headers=self.accept_headers) return deserialized
def test_parse_filter_params(self): query_params = MultiDict() query_params.add('type', 1) query_params.add('type', 2) query_params.add('test', 22) res = parse_filter_params(query_params, self.filterable) self.assertEqual({'type': [1, 2]}, res)
def test_reset_fail(self): """ Test the flow of the module if we complete the self assessment step and then reset Since the problem only allows one attempt, should fail. @return: """ assessment = [0, 1] # Simulate a student saving an answer self._handle_ajax("save_answer", {"student_answer": self.answer}) # Mock a student submitting an assessment assessment_dict = MultiDict({'assessment': sum(assessment)}) assessment_dict.extend(('score_list[]', val) for val in assessment) self._handle_ajax("save_assessment", assessment_dict) task_one_json = json.loads(self._module().task_states[0]) self.assertEqual(json.loads(task_one_json['child_history'][0]['post_assessment']), assessment) # Move to the next step in the problem self._handle_ajax("next_problem", {}) self.assertEqual(self._module().current_task_number, 0) html = self._module().render('student_view').content self.assertIsInstance(html, basestring) # Module should now be done rubric = self._handle_ajax("get_combined_rubric", {}) self.assertIsInstance(rubric, basestring) self.assertEqual(self._module().state, "done") # Try to reset, should fail because only 1 attempt is allowed reset_data = json.loads(self._handle_ajax("reset", {})) self.assertEqual(reset_data['success'], False)
def test_multiple_values(self): formdata = MultiDict() formdata.add('items', '1') formdata.add('items', '2') form = self.Form(formdata) assert form.items.data == ['1', '2'] assert form.validate()
def test_jsonify_multidict(self): data = MultiDict() data.add('a', 1) data.add('a', 2) data.add('b', 3) json_data = jsonify.encode(data) self.assertEqual('{"a": [1, 2], "b": 3}', json_data)
def test_repeated_argument(self): params = MultiDict(verb='a') params.add('repeated', 'b') params.add('repeated', 'b') self.assertRaises(BadArgument, views._check_params, params, ['repeated'])
def ignore_request_params_fields (request_params): result_data = MultiDict() for name, value in request_params.items(): if value != "IGNORE-THIS-FIELD": result_data.add(name, value) return result_data
def test_a_list_field_can_have_a_single_value(self): schema = QueryParamSchema() params = MultiDict() params.add("list_field", "first") parsed = validate_query_params(schema, params) assert parsed.getall("list_field") == ["first"]
def test_with_an_ordering(self, monkeypatch, db_request, page): params = MultiDict({"q": "foo bar", "o": "-created"}) if page is not None: params["page"] = page db_request.params = params sort = pretend.stub() suggest = pretend.stub( sort=pretend.call_recorder(lambda *a, **kw: sort), ) es_query = pretend.stub( suggest=pretend.call_recorder(lambda *a, **kw: suggest), ) db_request.es = pretend.stub( query=pretend.call_recorder(lambda *a, **kw: es_query) ) page_obj = pretend.stub(page_count=(page or 1) + 10) page_cls = pretend.call_recorder(lambda *a, **kw: page_obj) monkeypatch.setattr(views, "ElasticsearchPage", page_cls) url_maker = pretend.stub() url_maker_factory = pretend.call_recorder(lambda request: url_maker) monkeypatch.setattr(views, "paginate_url_factory", url_maker_factory) assert search(db_request) == { "page": page_obj, "term": params.get("q", ''), "order": params.get("o", ''), "applied_filters": [], "available_filters": [], } assert page_cls.calls == [ pretend.call(sort, url_maker=url_maker, page=page or 1), ] assert url_maker_factory.calls == [pretend.call(db_request)] assert db_request.es.query.calls == [ pretend.call( "multi_match", query="foo bar", fields=[ "name^2", "version", "author", "author_email", "maintainer", "maintainer_email", "home_page", "license", "summary", "description", "keywords", "platform", "download_url", ], ), ] assert es_query.suggest.calls == [ pretend.call( name="name_suggestion", term={"field": "name"}, text="foo bar", ), ] assert suggest.sort.calls == [ pretend.call("-created") ]
def test_it_keeps_only_last_value_for_non_sequence_fields(self): schema = QueryParamSchema() params = MultiDict() params.add("string_field", "first") params.add("string_field", "second") parsed = validate_query_params(schema, params) assert parsed.getall("string_field") == ["second"]
def test_it_does_not_include_unknown_fields(self): schema = QueryParamSchema() params = MultiDict() params.add("string_field", "include_me") params.add("unknown_field", "ignore_me") parsed = validate_query_params(schema, params) assert "unknown_field" not in parsed
def test_it_keeps_all_values_for_sequence_fields(self): schema = QueryParamSchema() params = MultiDict() params.add("list_field", "first") params.add("list_field", "second") parsed = validate_query_params(schema, params) assert parsed.getall("list_field") == ["first", "second"]
def test_does_not_remove_group_term_from_query_if_group_does_not_exist( self, pyramid_request, unparse ): query = MultiDict({"group": "does_not_exist"}) check_url(pyramid_request, query, unparse=unparse) assert query.get("group") == "does_not_exist" assert not unparse.called
def qs_add(self, *args, **kwargs): query = self.query.copy() if args: mdict = MultiDict(args[0]) for k, v in mdict.items(): query.add(k, v) for k, v in kwargs.items(): query.add(k, v) return self._copy(query=query)
def test_with_an_ordering(self, monkeypatch, db_request, page, order, expected): params = MultiDict({"q": "foo bar"}) if page is not None: params["page"] = page if order is not None: params["o"] = order db_request.params = params sort = pretend.stub() suggest = pretend.stub( sort=pretend.call_recorder(lambda *a, **kw: sort), ) es_query = pretend.stub( suggest=pretend.call_recorder(lambda *a, **kw: suggest), ) db_request.es = pretend.stub( query=pretend.call_recorder(lambda *a, **kw: es_query) ) page_obj = pretend.stub(page_count=(page or 1) + 10) page_cls = pretend.call_recorder(lambda *a, **kw: page_obj) monkeypatch.setattr(views, "ElasticsearchPage", page_cls) url_maker = pretend.stub() url_maker_factory = pretend.call_recorder(lambda request: url_maker) monkeypatch.setattr(views, "paginate_url_factory", url_maker_factory) assert search(db_request) == { "page": page_obj, "term": params.get("q", ''), "order": params.get("o", ''), "applied_filters": [], "available_filters": [], } assert page_cls.calls == [ pretend.call( sort if order is not None else suggest, url_maker=url_maker, page=page or 1, ), ] assert url_maker_factory.calls == [pretend.call(db_request)] assert db_request.es.query.calls == [ pretend.call( "dis_max", queries=self._gather_es_queries(params["q"]) ) ] assert es_query.suggest.calls == [ pretend.call( "name_suggestion", params["q"], term={"field": "name"}, ), ] assert suggest.sort.calls == [pretend.call(i) for i in expected]
def get_data(self, compact=True): data = MultiDict(self.raw_data) # XXX if compact: compact_data = MultiDict() for key, value in data.iteritems(): if value: compact_data.add(key, value) data = compact_data return data
def _w(*args, **kwargs): page = int(kwargs.pop(own_parameters["page"], 1)) real_items_per_page = int(kwargs.pop(own_parameters["items_per_page"], items_per_page)) # Iterate over all of the named arguments expected by the function f # if any of those arguments have values present in the kwargs dict, # add the value to the positional args list, and remove it from the # kwargs dict argvars = inspect.getargspec(f)[0][1:] if argvars: args = list(args) for i, var in enumerate(args): if i >= len(argvars): break var = argvars[i] if var in kwargs: if i + 1 >= len(args): args.append(kwargs[var]) else: args[i + 1] = kwargs[var] del kwargs[var] res = f(*args, **kwargs) if isinstance(res, dict) and name in res: additional_parameters = MultiDict() for key, value in request.params.iteritems(): if key not in own_parameters: additional_parameters.add(key, value) collection = res[name] # Use CustomPage if our extra custom arg was provided if items_first_page is not None: page_class = CustomPage else: page_class = Page page = page_class( collection, page, items_per_page=real_items_per_page, items_first_page=items_first_page, **additional_parameters.dict_of_lists() ) # wrap the pager so that it will render # the proper page-parameter page.pager = partial(page.pager, page_param=own_parameters["page"]) res[name] = page # this is a bit strange - it appears # as if c returns an empty # string for everything it dosen't know. # I didn't find that documented, so I # just put this in here and hope it works. if not hasattr(tmpl_context, "paginators") or type(tmpl_context.paginators) == str: tmpl_context.paginators = Bunch() tmpl_context.paginators[name] = page return res
def test_does_not_remove_group_term_from_query_if_group_does_not_exist(self, pyramid_request, unparse): query = MultiDict({'group': 'does_not_exist'}) check_url(pyramid_request, query, unparse=unparse) assert query.get('group') == 'does_not_exist' assert not unparse.called
def add(self, *args, **kwargs): '''Adds values to URL's query''' query = self.query.copy() if args: mdict = MultiDict(args[0]) for k, v in mdict.items(): query.add(k, v) for k, v in kwargs.items(): query.add(k, v) return self._copy(query=query)
def upload_request(self, files: dict, metadata=None, user=None): if metadata is None: metadata = '{}' fields = MultiDict({'metadata': metadata}) for name, content in files.items(): fs = FieldStorage() fs.file = BytesIO(content) fs.filename = name fields.add('file', fs) return self.generic_request(post=fields, user=user)
def test_mf_search(self): mdict = MultiDict() mdict.add('SearchUser[email]', 'other') request = testing.DummyRequest(mdict) request.matchdict['objname'] = 'user' response = mf_search(request) #users = json.loads(response.body) users = response assert(len(users) == 1) assert(users[0]['email'] == '*****@*****.**')
def test_does_not_remove_user_term_from_query_if_user_does_not_exist( self, pyramid_request, unparse, user_service ): query = MultiDict({"user": "******"}) user_service.fetch.return_value = None check_url(pyramid_request, query, unparse=unparse) assert query.get("user") == "jose" assert not unparse.called
def _dict_to_multidict(dict_): """Convert a validated query param dict back to a ``MultiDict``.""" result = MultiDict() for key, value in dict_.items(): if isinstance(value, list): for item in value: result.add(key, item) else: result.add(key, value) return result
def dict2mdict(values): "convert dict to multidict" muld = MultiDict() for key in values: if (key in BOOLFIELDS and (values[key] == '' or values[key] == 'False' or values[key] is None)): continue muld.add(key, values[key]) return muld
def dummy_post(dbtransaction): from pyramid.testing import DummyRequest from webob.multidict import MultiDict req = DummyRequest() req.method = 'POST' md = MultiDict() md.add('title', 'dummy title') md.add('text', 'dummy text') req.POST = md return req
def test_remove_multiple_deterrent_attributes(self): params = MultiDict({'pling_id':'pling_id_value', 'feedback_attribute':'deterrent', 'deterrent_value':'Cost', 'plingback_type':'automated_testing'}) params.add('deterrent_value', 'Transport') tf = self.configure_triple_factory('/api/plingbacks', params=params) tf.add_attribute() self.failUnless(len([x for x in tf.request.context.store]) == 2) tf.remove_attribute('deterrent') self.failUnless(len([x for x in tf.request.context.store]) == 0)
def test_multidict_init(): d = MultiDict([('a', 'b')], c=2) assert repr(d) == "MultiDict([('a', 'b'), ('c', 2)])" assert d == MultiDict([('a', 'b')], c=2) # TypeError: MultiDict can only be called with one positional argument with pytest.raises(TypeError): MultiDict(1, 2, 3) # TypeError: MultiDict.view_list(obj) takes only actual list objects, not None with pytest.raises(TypeError): MultiDict.view_list(None)
def __init__(self, request, formdata=None, obj=None, prefix='', **kwargs): self.request = request if request.stash: if formdata is None: formdata = MultiDict() else: formdata = deepcopy(formdata) formdata.update(request.stash['post']) super(FloofForm, self).__init__(formdata=formdata, obj=obj, prefix=prefix, **kwargs)
def test_overrides_group_term_for_group_search_requests( self, parse, pyramid_request): # If the query sent to a group search page includes a group, we override # it, because otherwise we'll display the union of the results for those # two groups, which makes no sense. parse.return_value = MultiDict({ "foo": "bar", "group": "whattheusersent" }) pyramid_request.matched_route.name = "group_read" pyramid_request.matchdict["pubid"] = "abcd1234" pyramid_request.GET["q"] = "giraffe" result = extract(pyramid_request, parse=parse) assert result.dict_of_lists() == { "foo": ["bar"], "group": ["abcd1234"] }
def test_filter_by_pid_not_found(self, req, db_session, factories): """ It should not return specimen because filter criteria does not match any specimen """ from webob.multidict import MultiDict pid = u'XXX-XXX-XX' # Sample must be from the current working location location = factories.LocationFactory.create() factories.SpecimenFactory.create(state__name='pending-draw', patient__pid=pid, location=location) db_session.flush() req.GET = MultiDict([('pid', u'YYY-YYY-YY')]) res = self._call_fut(location, req, state='pending-draw') assert not res['has_specimen']
def test_path_validations_with_invalid_path_inputs(path, scope, progress_state, dummy_request): article = Article(path=path) dummy_request.params = dummy_request.POST = MultiDict({ 'csrf_token': dummy_request.session.get_csrf_token(), 'title': 'Title', 'path': path, 'scope': scope, 'progress_state': progress_state['value'], }) form = build_article_settings_form(dummy_request, article) assert not form.validate() assert form.path.errors
def test_save_account(self, pyramid_services, user_service, db_request): breach_service = pretend.stub() pyramid_services.register_service(IUserService, None, user_service) pyramid_services.register_service(IPasswordBreachedService, None, breach_service) user = UserFactory.create(name="old name") EmailFactory.create(primary=True, verified=True, public=True, user=user) db_request.user = user db_request.method = "POST" db_request.path = "/manage/accounts/" db_request.POST = MultiDict({"name": "new name", "public_email": ""}) views.ManageAccountViews(db_request).save_account() user = user_service.get_user(user.id) assert user.name == "new name" assert user.public_email is None
def test_print_by_specimen_all_states(self, req, db_session, config, factories, check_csrf_token, state): from webob.multidict import MultiDict from occams_lims.views.aliquot import ALIQUOT_LABEL_QUEUE location = factories.LocationFactory.create() specimen_state = factories.SpecimenStateFactory.create(name=state) specimen = factories.SpecimenFactory.create(state=specimen_state, location=location) db_session.flush() context = specimen.location req.session[ALIQUOT_LABEL_QUEUE] = set([specimen.id]) req.method = 'POST' req.POST = MultiDict([('print', '')]) res = self._call_fut(context, req) assert res.content_type == 'application/pdf' assert len(req.session[ALIQUOT_LABEL_QUEUE]) == 0
def test_raises_400_with_pagenum_type_str(self, monkeypatch, db_request): params = MultiDict({"page": "abc"}) db_request.params = params es_query = pretend.stub() db_request.es = pretend.stub(query=lambda *a, **kw: es_query) page_obj = pretend.stub(page_count=10) page_cls = pretend.call_recorder(lambda *a, **kw: page_obj) monkeypatch.setattr(views, "ElasticsearchPage", page_cls) url_maker = pretend.stub() url_maker_factory = pretend.call_recorder(lambda request: url_maker) monkeypatch.setattr(views, "paginate_url_factory", url_maker_factory) with pytest.raises(HTTPBadRequest): search(db_request) assert page_cls.calls == []
def test_it_no_comments(self): from karl.models.interfaces import ICommunity from karl.models.interfaces import ISite from zope.interface import directlyProvides from karl.testing import DummyProfile from repoze.workflow.testing import registerDummyWorkflow site = testing.DummyModel() site['test'] = context = testing.DummyModel() directlyProvides(context, ICommunity, ISite) registerDummyWorkflow('security') context.catalog = {'creation_date': DummyCreationDateIndex()} context['profiles'] = profiles = testing.DummyModel() profiles['dummy'] = DummyProfile(title='Dummy Creator') from webob.multidict import MultiDict request = testing.DummyRequest( params=MultiDict({'year': 2009, 'month': 4})) from karl.utilities.interfaces import IKarlDates karl.testing.registerUtility(dummy, IKarlDates) from datetime import datetime entry = testing.DummyModel( creator='dummy', title='Dummy Entry', description='Some words', created=datetime(2009, 4, 15)) from zope.interface import directlyProvides from karl.content.interfaces import IBlogEntry directlyProvides(entry, IBlogEntry) entry['comments'] = testing.DummyModel() context['e1'] = entry def dummy_byline_info(context, request): return context from zope.interface import Interface from karl.content.views.interfaces import IBylineInfo karl.testing.registerAdapter(dummy_byline_info, (Interface, Interface), IBylineInfo) response = self._callFUT(context, request) self.assertEqual(len(response['entries']), 1) self.assertEqual(response['entries'][0]['title'], 'Dummy Entry') self.assertEqual(response['entries'][0]['creator_href'], 'http://example.com/test/e1/') self.assertEqual(response['entries'][0]['href'], 'http://example.com/test/e1/') self.assertEqual(response['entries'][0]['creator_title'], 'Dummy Creator')
def test_creator_not_found(self): from webob.multidict import MultiDict context = testing.DummyModel() context.catalog = {} context['profiles'] = testing.DummyModel() request = testing.DummyRequest(params=MultiDict({'body':'yo'})) from zope.interface import Interface from karl.models.interfaces import ICatalogSearch from karl.views.interfaces import IAdvancedSearchResultsDisplay from repoze.lemonade.testing import registerContentFactory registerContentFactory(DummyContent, IDummyContent) karltesting.registerAdapter(DummySearch, (Interface), ICatalogSearch) karltesting.registerAdapter(DummySearchResultsDisplay, (Interface, Interface), IAdvancedSearchResultsDisplay) result = self._callFUT(context, request) self.assertEqual(result['terms'], ['yo']) self.assertEqual(len(result['results']), 1)
def test_multiple2__convert_to_dict_list__order_also_same(): from webob.multidict import MultiDict mdict = MultiDict( [ ("name", "foo"), ("name", "bar"), ("name", "boo"), ("country", "jp"), ("country", "us"), ("country", "ch"), ] ) result = _callFUT(mdict) assert result == [ {"name": "foo", "country": "jp"}, {"name": "bar", "country": "us"}, {"name": "boo", "country": "ch"}, ]
def application_ownership_transfer(request): """ Allows application owner to transfer application ownership to other user """ resource = request.context.resource form = forms.ChangeApplicationOwnerForm( MultiDict(request.safe_json_body or {}), csrf_context=request ) form.password.user = request.user if form.validate(): user = UserService.by_user_name(form.user_name.data) user.resources.append(resource) # remove integrations to not leak security data of external applications for integration in resource.integrations[:]: resource.integrations.remove(integration) request.session.flash(_("Application transfered")) else: return HTTPUnprocessableEntity(body=form.errors_json) return True
def test_with_batch(self): from webob.multidict import MultiDict context = testing.DummyModel() context.catalog = {} context['profiles'] = profiles = testing.DummyModel() profiles['tweedle dee'] = testing.DummyModel(title='Tweedle Dee') request = testing.DummyRequest( params=MultiDict({'body':'yo', 'batch_start': '20', 'batch_size': '20'}) ) from zope.interface import Interface from karl.models.interfaces import ICatalogSearch from repoze.lemonade.testing import registerContentFactory registerContentFactory(DummyContent, IDummyContent) karltesting.registerAdapter(DummySearch, (Interface), ICatalogSearch) result = self._callFUT(context, request) self.failIf('batch' in result['kind_knob'][0]['url']) self.failIf('batch' in result['since_knob'][0]['url'])
def test_replies_are_ordered_most_recently_updated_first( self, Annotation, pyramid_request ): annotation = Annotation(shared=True) now = datetime.datetime.now() five_mins = datetime.timedelta(minutes=5) reply_1 = Annotation( updated=now + (five_mins * 2), references=[annotation.id], shared=True ) reply_2 = Annotation(updated=now, references=[annotation.id], shared=True) reply_3 = Annotation( updated=now + five_mins, references=[annotation.id], shared=True ) result = search.Search(pyramid_request, separate_replies=True).run( MultiDict({}) ) assert result.reply_ids == [reply_1.id, reply_3.id, reply_2.id]
def test_upload_fails_with_unsupported_wheel_plat(self, pyramid_config, db_request, plat): pyramid_config.testing_securitypolicy(userid=1) user = UserFactory.create() project = ProjectFactory.create() release = ReleaseFactory.create(project=project, version="1.0") RoleFactory.create(user=user, project=project) filename = "{}-{}-cp34-none-{}.whl".format( project.name, release.version, plat, ) db_request.POST = MultiDict({ "metadata_version": "1.2", "name": project.name, "version": release.version, "filetype": "bdist_wheel", "pyversion": "cp34", "md5_digest": "335c476dc930b959dda9ec82bd65ef19", "content": pretend.stub( filename=filename, file=io.BytesIO(b"A fake file."), ), }) with pytest.raises(HTTPBadRequest) as excinfo: pypi.file_upload(db_request) resp = excinfo.value assert resp.status_code == 400 assert resp.status == "400 Binary wheel for an unsupported platform."
def test_edit_banner_with_with_no_image(self): """ Ensure the banner object is gone when there is no image. """ # Create a dummy mod. mod = create_mod(self.contributor).save() # Add a banner mod.banner = Banner() mod.banner.image = IMG mod.save() # Create request request = DummyRequest( matchdict={'id': mod.id}, params=MultiDict({'text_color': '#000000', 'submit': ''}), matched_route=Struct(name='editmodbanner') ) # Run self.makeOne(request).editbanner() # Check if no banner exists mod.reload() self.assertIsNone(mod.banner)
def test_search_reuses_group_annotation_count_if_able( self, controller, factories, test_group, test_user, query, annotation_stats_service, pyramid_request, ): """ In cases where the annotation count returned from search is the same calc as the annotation count that would be returned from the stats service, re-use that value rather than executing another query inside the stats service. """ controller.parsed_query_params = MultiDict({"group": test_group}) result = controller.search()["stats"] annotation_stats_service.group_annotation_count.assert_not_called() assert result["annotation_count"] == 200
def test_filter_by_pid_found(self, req, db_session, factories): """ It should return aliquot matching the cycle filter criteria """ from webob.multidict import MultiDict pid = u'XXX-XXX-XX' # Samole must be from the current working location location = factories.LocationFactory.create() factories.AliquotFactory.create(state__name='pending', location=location, specimen__patient__pid=pid, specimen__location=location, specimen__state__name='complete') db_session.flush() req.GET = MultiDict([('pid', pid)]) res = self._call_fut(location, req, state='pending') assert res['has_aliquot']
def test_create_skip_post(self): self.request.context = self.municipality self.request.method = 'POST' self.request.POST = MultiDict([ ('skip_type', 'Z'), ('small_length', '20'), ('large_length', '30'), ('small_breadth', '16'), ('large_breadth', '20') ]) num_skips = Skip.count() result = self.views.create_skip() self.assertIsInstance(result, HTTPFound) self.assertEqual(Skip.count(), num_skips + 1) skip = Skip.newest() self.assertEqual( result.location, self.request.route_url('skips', traverse=(skip.id, 'edit'))) municipality = Municipality.get(Municipality.name == "Mukono") self.assertEqual(skip.municipality, municipality)
def test_update_report(self): self._add_site_report() report_date = datetime.datetime(YEAR, MONTH, DAY) initial_count = SiteReport.count() # use existing municipality instance state municipality = self.municipality municipality.vehicle_count = MagicMock(return_value=15) self.request.context = municipality self.request.method = 'POST' self.request.POST = MultiDict([ ('start', '{}-{}-{}'.format(YEAR, MONTH, 1)), ('end', '{}-{}-{}'.format(YEAR, MONTH, 31))]) response = self.views.save_site_report() self.assertIsInstance(response, HTTPFound) self.assertEqual(SiteReport.count(), initial_count) site_report = SiteReport.get_report_by_date( report_date, self.municipality) self.assertEqual(site_report.report_json['vehicle_count'], 15)
def test_list(self, req, db_session, factories): """ It should return a list of external services JSON records """ from webob.multidict import MultiDict study = factories.StudyFactory.create() cycle = factories.CycleFactory.create(study=study) cycle.__parent__ = study factories.ExternalServiceFactory.create(study=study, title=u'test-service') db_session.flush() req.GET = MultiDict([]) res = self._call_fut(cycle, req) assert res['external_services'][0]['title'] == u'test-service' assert len(res['external_services']) == 1
def users_self(request): """ Updates user personal information """ if request.method == "PATCH": form = forms.gen_user_profile_form()(MultiDict( request.unsafe_json_body), csrf_context=request) if form.validate(): form.populate_obj(request.user) request.session.flash(_("Your profile got updated.")) else: return HTTPUnprocessableEntity(body=form.errors_json) return request.user.get_dict( exclude_keys=[ "security_code_date", "notes", "security_code", "user_password" ], extended_info=True, )
def test_call_fail( self, req, db_session, ): """ It should return an validation error string if the cycles are invalid """ from webob.multidict import MultiDict from occams_studies import models patient = models.Patient(site=models.Site(name=u'ucsd', title=u'UCSD'), pid=u'12345') db_session.add_all([patient]) db_session.flush() req.GET = MultiDict([('cycles', '123')]) res = self._call_fut(patient['visits'], req) assert 'not found' in res.lower()
def test_add_mod_view_with_bad_input(self): """ Ensure the add mod page is validated by inputting bad info. """ # Create request request = DummyRequest(params=MultiDict({ 'author': 'SAuthor', 'url': 'somehomepage', 'target': 'both', 'submit': '' })) # Get result and make sure it's not HTTPFound try: result = self.makeOne(request).addmod() except httpexceptions.HTTPFound: self.fail('Bad input was accepted.') # Check if the correct errors are returned self.assertDictEqual(result['f'].errors, { 'name': ['This field is required.'], 'url': ['Invalid URL.'] })
def test_it_returns_replies(self, pyramid_request, search_run, annotation_json_service): pyramid_request.params = NestedMultiDict( MultiDict({"_separate_replies": "1"})) search_run.return_value = SearchResult(1, ["row-1"], ["reply-1", "reply-2"], {}) expected = { "total": 1, "rows": annotation_json_service.present_all_for_user( annotation_ids=["row-1"], user=pyramid_request.user), "replies": annotation_json_service.present_all_for_user( annotation_ids=["reply-1", "reply-2"], user=pyramid_request.user), } assert views.search(pyramid_request) == expected
def test_it_restricted(self): self.jobquery.restricted = True params = MultiDict(scenario=[{'type': 'phase1', 'steps': '2'}, {'type': 'phase2', 'steps': '1'}] ) query = self.jobquery.metabolize(params) script = "{magma} metabolize -g --scenario scenario.csv" script += " --call_back_url '/' --time_limit 3 {db}\n" expected_query = JobQuery(directory=self.jobdir, prestaged=['scenario.csv'], script=script, status_callback_url='/', restricted=True, ) self.assertEqual(query, expected_query) self.assertMultiLineEqual('phase1,2\nphase2,1\n', self.fetch_file('scenario.csv') )
def transform(self, fn, decode=False): """Accepts a function, getting a key, val and returning a new pair of key, val and applies the function to all header, value pairs in the message. """ changed = [False] def tracking_fn(key, val): new_key, new_val = fn(key, val) if new_val != val or new_key != key: changed[0] = True return new_key, new_val v = MultiDict( tracking_fn(key, val) for key, val in self.iteritems(raw=not decode)) if changed[0]: self._v = v self.changed = True
def test_delete_version_with_mod_file_url(self): """ Ensure delete version works with no mod_file. """ # Create a dummy mod mod = create_mod(self.contributor).save() # Create a modversion self.makeOne(matchrequest( params=MultiDict(mock_version_data(mod_file_url=URL)), id=mod.id)).addversion() # Reload the mod mod.reload() # Get the new modversion v = mod.versions[0] # Create request to delete the new modversion request = matchrequest(id=v.id) # Run self.makeOne(request).deleteversion() # Reload the mod again mod.reload() # Check if the version's gone self.assertFalse(mod.versions)
def test_replies_that_dont_match_the_search_arent_included( self, factories, pyramid_request, Annotation): """Replies that don't match the search query aren't included. Not even if the top-level annotations that they're replies to _are_ included. """ user = factories.User() reply_user = factories.User() annotation = Annotation(userid=user.userid, shared=True) reply = Annotation(userid=reply_user.userid, references=[annotation.id], shared=True) result = search.Search(pyramid_request).run( # Search for annotations from ``user``, so that ``reply_user``'s # reply doesn't match. params=MultiDict({"user": user.userid})) assert reply.id not in result.annotation_ids
def test_create_banner(self, db_request, banner_data): db_request.method = "POST" db_request.POST = MultiDict(banner_data) db_request.session = pretend.stub( flash=pretend.call_recorder(lambda *a, **kw: None)) db_request.route_url = pretend.call_recorder( lambda r: "/admin/banners/") assert db_request.db.query(Banner).count() == 0 resp = views.create_banner(db_request) assert db_request.db.query(Banner).count() == 1 assert resp.status_code == 303 assert resp.location == "/admin/banners/" assert db_request.session.flash.calls == [ pretend.call("Added new banner 'Sample Banner'", queue="success") ] assert db_request.route_url.calls == [ pretend.call("admin.banner.list") ]
def test_skip_validation_if_from_complete(self, db_session): from webob.multidict import MultiDict from occams_datastore import models as datastore from occams_forms.renderers import \ make_form, states, modes, entity_data schema = self._make_schema(db_session) entity = datastore.Entity( schema=schema, state=( db_session.query(datastore.State) .filter_by(name=states.COMPLETE) .one())) Form = make_form( db_session, schema, entity=entity, transition=modes.ALL) formdata = MultiDict({ 'ofworkflow_-state': states.PENDING_CORRECTION, }) form = Form(formdata, data=entity_data(entity)) assert form.validate(), form.errors
def test_multidict_to_list(self): from price_watch.utilities import multidict_to_list from webob.multidict import MultiDict multidict = MultiDict(( ('price_value', 55.6), ('url', 'http://howies.com/products/milk/4'), ('product_title', u'Молоко Красная Цена у/паст. 3.2% 1л'.encode('utf-8')), ('merchant_title', "Howie's grocery"), ('reporter_name', 'Jack'), ('price_value', 45.3), ('url', 'http://howies.com/products/milk/5'), ('product_title', u'Молоко Красная Цена у/паст. 1% 1л'.encode('utf-8')), ('merchant_title', "Howie's grocery"), ('reporter_name', 'Jack'), )) dict_list = multidict_to_list(multidict) self.assertEqual(2, len(dict_list))