PyHamcrest fails with the following error
I have this code using pyhamcrest(https://github.com/hamcrest/PyHamcrest) library:
def check_search(url, voicemail, hidden, field, term):
response = url.get(search=term)
assert_that(response.items, has_item(has_entry(field, voicemail[field])))
assert_that(response.items, is_not(has_item(has_entry(field, hidden[field]))))
response = url.get(**{field: voicemail[field]})
assert_that(response.items, has_item(has_entry('id', voicemail['id'])))
assert_that(response.items, is_not(has_item(has_entry('id', hidden['id']))))
When I run the tests, I get the following error:
2022-01-12 03:03:06.113981 | vm-debian-10-m1s | assert_that(response.items, is_not(has_item(has_entry('id', hidden['id']))))
2022-01-12 03:03:06.113995 | vm-debian-10-m1s | AssertionError:
2022-01-12 03:03:06.114009 | vm-debian-10-m1s | Expected: not a sequence containing a dictionary containing ['id': <24>]
2022-01-12 03:03:06.114025 | vm-debian-10-m1s | but: but was <[{'id': 22, 'tenant_uuid': 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeee1', 'number': '123456789123456789', 'firstname': None, 'lastname': None, 'password': None, 'language': None, 'preprocess_subroutine': None, 'description': None, 'links': [{'rel': 'agents', 'href': 'http://127.0.0.1:49157/1.1/agents/22'}], 'queues': [], 'skills': [], 'users': []}, {'id': 24, 'tenant_uuid': 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeee1', 'number': '2310', 'firstname': 'hidden', 'lastname': 'hidden', 'password': None, 'language': None, 'preprocess_subroutine': 'hidden', 'description': None, 'links': [{'rel': 'agents', 'href': 'http://127.0.0.1:49157/1.1/agents/24'}], 'queues': [], 'skills': [], 'users': []}, {'id': 25, 'tenant_uuid': 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeee1', 'number': '0319', 'firstname': 'search', 'lastname': 'search', 'password': None, 'language': None, 'preprocess_subroutine': 'search', 'description': None, 'links': [{'rel': 'agents', 'href': 'http://127.0.0.1:49157/1.1/agents/25'}], 'queues': [], 'skills': [], 'users': []}]>
Anyone knows how to fix it? Thanks.
do you know?
how many words do you know
See also questions close to this topic
-
Python File Tagging System does not retrieve nested dictionaries in dictionary
I am building a file tagging system using Python. The idea is simple. Given a directory of files (and files within subdirectories), I want to filter them out using a filter input and tag those files with a word or a phrase.
If I got the following contents in my current directory:
data/ budget.xls world_building_budget.txt a.txt b.exe hello_world.dat world_builder.spec
and I execute the following command in the shell:
py -3 tag_tool.py -filter=world -tag="World-Building Tool"
My output will be:
These files were tagged with "World-Building Tool": data/ world_building_budget.txt hello_world.dat world_builder.spec
My current output isn't exactly like this but basically, I am converting all files and files within subdirectories into a single dictionary like this:
def fs_tree_to_dict(path_): file_token = '' for root, dirs, files in os.walk(path_): tree = {d: fs_tree_to_dict(os.path.join(root, d)) for d in dirs} tree.update({f: file_token for f in files}) return tree
Right now, my dictionary looks like this:
key:''
.In the following function, I am turning the empty values
''
into empty lists (to hold my tags):def empty_str_to_list(d): for k,v in d.items(): if v == '': d[k] = [] elif isinstance(v, dict): empty_str_to_list(v)
When I run my entire code, this is my output:
hello_world.dat ['World-Building Tool'] world_builder.spec ['World-Building Tool']
But it does not see
data/world_building_budget.txt
. This is the full dictionary:{'data': {'world_building_budget.txt': []}, 'a.txt': [], 'hello_world.dat': [], 'b.exe': [], 'world_builder.spec': []}
This is my full code:
import os, argparse def fs_tree_to_dict(path_): file_token = '' for root, dirs, files in os.walk(path_): tree = {d: fs_tree_to_dict(os.path.join(root, d)) for d in dirs} tree.update({f: file_token for f in files}) return tree def empty_str_to_list(d): for k, v in d.items(): if v == '': d[k] = [] elif isinstance(v, dict): empty_str_to_list(v) parser = argparse.ArgumentParser(description="Just an example", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument("--filter", action="store", help="keyword to filter files") parser.add_argument("--tag", action="store", help="a tag phrase to attach to a file") parser.add_argument("--get_tagged", action="store", help="retrieve files matching an existing tag") args = parser.parse_args() filter = args.filter tag = args.tag get_tagged = args.get_tagged current_dir = os.getcwd() files_dict = fs_tree_to_dict(current_dir) empty_str_to_list(files_dict) for k, v in files_dict.items(): if filter in k: if v == []: v.append(tag) print(k, v) elif isinstance(v, dict): empty_str_to_list(v) if get_tagged in v: print(k, v)
-
Actaully i am working on a project and in it, it is showing no module name pip_internal plz help me for the same. I am using pycharm(conda interpreter
File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 196, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 86, in _run_code exec(code, run_globals) File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\Scripts\pip.exe\__main__.py", line 4, in <module> File "C:\Users\pjain\AppData\Local\Programs\Python\Python310\lib\site-packages\pip\_internal\__init__.py", line 4, in <module> from pip_internal.utils import _log
I am using pycharm with conda interpreter.
-
Looping the function if the input is not string
I'm new to python (first of all) I have a homework to do a function about checking if an item exists in a dictionary or not.
inventory = {"apple" : 50, "orange" : 50, "pineapple" : 70, "strawberry" : 30} def check_item(): x = input("Enter the fruit's name: ") if not x.isalpha(): print("Error! You need to type the name of the fruit") elif x in inventory: print("Fruit found:", x) print("Inventory available:", inventory[x],"KG") else: print("Fruit not found") check_item()
I want the function to loop again only if the input written is not string. I've tried to type return Under print("Error! You need to type the name of the fruit") but didn't work. Help
-
Kotlin Coroutines Unit Testing
Im trying to test this suspend function:
suspend fun <T> getResult(call: suspend () -> Response<T>): Resource<T> { val response = call() val body = response.body() val code = response.code() if (response.isSuccessful) { Log.d(Cybrid.instance.tag, "Data: ${response.code()} - ${response.body()}") return Resource.success(body!!, code) } else if (response.code() == HTTP_UNAUTHORIZED || response.code() == HTTP_FORBIDDEN) { Cybrid.instance.let { cybrid -> cybrid.listener.let { cybrid.invalidToken = true it?.onTokenExpired() } } Log.e(Cybrid.instance.tag, "Error - Something wrong with TOKEN : ${response.code()} ${response.message()}") return Resource.error(response.message(), code=response.code()) } else { Log.e(Cybrid.instance.tag, "Error - Other: ${response.code()} ${response.message()} :: ${response.raw()}") return Resource.error(message = response.message(), data= response.body(), code= response.code()) } }
With this Unit Test Case, all it cover except line 13 , I dont know how to cover the line!!!
@ExperimentalCoroutinesApi @Test fun get400ErrorServerTest() = runBlocking { Cybrid.instance.setBearer("Bearer") val pricesService = AppModule.getClient().createService(PricesApi::class.java) val result = getResult { pricesService.listPrices() } Assert.assertNotNull(result) Assert.assertEquals(result.code, 400) Assert.assertNull(result.data) }
The coverage report says:
Some idea to get coverage for line 13 ??? Thnanks
-
Is there any way to mock API responses using snapshots?
I'm currently trying to find a good way to mock API responses for a subset of end-to-end tests, and was thinking it would be swell if there was a way to take snapshots when the backend services are healthy, and then use those snap-shotted responses in place of making actual HTTP requests when the tests are being run. Does anyone know if a library exists for this sort of thing?
Basically, I'd like to do something like the following:
it('does something', () => { const data = process.env.UPDATE_SNAPSHOTS ? getDataFromServer() : getDataFromSnapshot(); saveSnapshot(data); // Saves snapshot data to file system like jest // Test things using "data" });
It would be great if I could just use jest for this, since I'm using jest anyway. But as far as I can tell, jest doesn't have any file-based snapshot methods besides
toMatchSnapshot()
and I really need to be able tosaveSnapshot()
andreadSnapshot()
arbitrarily. -
Library functions in Inspec Test
Team --
I have a ruby library helper in which I have defined multiple functions/methods. How do I reference those in
Chef
Inspec
tests?def interface_name # some code with logic end
In my specific use case, I am checking to see if a custom networking device was specified as a JSON parameter, and if it was, I am validating it make sure its real (incase they misspelled it) and also gathering its IP and state and other data as reported by
Ohai
This is what I have so far, but I'm not sure if this is correct
describe file('/path/to/custom_attributes.json') do it { should exist } unless json('/path/to/custom_attributes.json').empty? do its(['networking']['interface_name']) { should_not be_empty } interface_name = file(json('/path/to/custom_attributes.json').params['networking']['interface_name']) end end describe file('/etc/NetworkManager/system-connections/wired_connection') do unless interface_name.empty? its('content') { should_not match(/^interface-name=wl.*/mx) } end its('content') { should match(%r{ca-cert=/etc/ssl/certs/ca-certificates\.crt}mx) } its('content') { should match(/id=\.corp.*type=ethernet.*autoconnect-priority=100.*dns-search=corp\.domain.com.*/mx) } end end
The problem / question is that if I gather the parameter directly from the JSON file, then I am bypassing all the validation logic that I'm doing in the library, which defeats the purpose. So, how do I get access to that library function/method in the Inspec test?
For reference, here is the function:
def interface_name file = '/path/to/custom_attributes.json' if File.exist?(file) && !File.stat(file).zero? attributes = JSON.parse(File.read(file)) device_name = attributes['networking']['interface_name'] if device_name && !device_name.empty? && networking_devices.include?(device_name) interface = device_name Chef::Log.info("Valid custom interface provided, using \"#{device_name}\".") else Chef::Log.debug("Invalid interface (\"#{device_name}\") provided. Valid options are: \"#{networking_devices.keys}\"") interface = nil end else Chef::Log.debug('No custom interface provided.') end interface rescue JSON::ParserError nil end
-
C++ asserts on try-catch
My task is to create a program where I have to catch exceptions, because I haven't worked with them yet, I don't know how to set them up for these asserts. https://onecompiler.com/cpp/3y2sqxb2k
//in main asserts
try { a . addField ( "m_Status", CDataTypeInt () ); assert ( "addField: missing exception!" == nullptr ); } catch ( const invalid_argument & e ) { assert ( e . what () == "Duplicate field: m_Status"sv ); } try { cout << a . field ( "m_Fail" ) << endl; assert ( "field: missing exception!" == nullptr ); } catch ( const invalid_argument & e ) { assert ( e . what () == "Unknown field: m_Fail"sv ); } try { CDataTypeEnum en; en . add ( "FIRST" ) . add ( "SECOND" ) . add ( "FIRST" ); assert ( "add: missing exception!" == nullptr ); } catch ( const invalid_argument & e ) { assert ( e . what () == "Duplicate enum value: FIRST"sv ); }
I capture them in the program like this. Here are 3 parts of the program where I process them
class CDataTypeEnum : public CDataType { CDataTypeEnum& add(const string & x) { for(vector<string>::iterator it = db.begin(); it != db.end(); ++it) { if(*it == x) { CSyntaxException e("Duplicate enum value: " + x); throw e; } } db.push_back(x); return *this; }
...
class CDataTypeStruct : public CDataType { public: CDataTypeStruct & addField(const string& name, const CDataType & type) { CDataType * tmp = type.clone(); shared_ptr<CDataType> tmpp (tmp); for(vector<pair<string, shared_ptr<CDataType> > >::iterator it = db.begin(); it != db.end(); ++it) { if (it->first == name) { throw CSyntaxException("Duplicate field: " + name); } }
..
CDataType & field(const string& n) const { for(vector<pair<string, shared_ptr<CDataType> > >::const_iterator it = db.begin(); it != db.end(); ++it) { if (it->first == n) { return *(it->second); } } throw CSyntaxException("Unknown field: " + n); }
-
Can not add Seaborn dependency using Poetry on Python
I'm trying to add Seaborn dependency to my module, using Poetry.
I've tried it on different ways, but always without success, maybe I'm doing it wrong.
Here's my current toml config file:
[tool.poetry] name = "seaborn" version = "0.1.0" description = "" authors = ["me"] [tool.poetry.dependencies] python = "3.9.6" pandas = "^1.4.1" jupyter = "^^.0.0" scipy = "1.7.0" numpy = "^1.22.3" [tool.poetry.dev-dependencies] pytest = "^5.2" [build-system] requires = ["poetry-core>=1.0.0"] build-backend = "poetry.core.masonry.api"
I've tried on the CLI:
poetry add seaborn
But no success. Here's the output
poetry add seaborn Using version ^0.11.2 for seaborn Updating dependencies Resolving dependencies... (0.0s) AssertionError at ~/.pyenv/versions/3.10.0/lib/python3.10/site-packages/poetry/mixology/incompatibility.py:111 in __str__ 107│ ) 108│ 109│ def __str__(self): 110│ if isinstance(self._cause, DependencyCause): → 111│ assert len(self._terms) == 2 112│ 113│ depender = self._terms[0] 114│ dependee = self._terms[1] 115│ assert depender.is_positive()
If I try to add it to the
toml
config file likeseaborn = "^0.0.1"
The out put is very similar:poetry update Updating dependencies Resolving dependencies... (0.0s) AssertionError at ~/.pyenv/versions/3.10.0/lib/python3.10/site-packages/poetry/mixology/incompatibility.py:111 in __str__ 107│ ) 108│ 109│ def __str__(self): 110│ if isinstance(self._cause, DependencyCause): → 111│ assert len(self._terms) == 2 112│ 113│ depender = self._terms[0] 114│ dependee = self._terms[1] 115│ assert depender.is_positive()
Can anyone help me?
Thank you so much!
-
in golang how to access data from a list of maps
Using Avi Go SDK to get gslbservice as below,
var gslbmap map[string]interface{} err = aviClient.AviSession.GetObjectByName("gslbservice", "GSLBNAME", &gslbmap) if err != nil { t.Error(err) }
And it get store the metadata in a map,
map[_last_modified:1651222310086902 controller_health_status_enabled:true created_by:null description:null domain_names:[DOMAINNAME] down_response:map[type:GSLB_SERVICE_DOWN_RESPONSE_ALL_RECORDS] enabled:true groups:[map[algorithm:GSLB_ALGORITHM_ROUND_ROBIN members:[map[cluster_uuid:xxxxxxxxxx enabled:true fqdn:HOST ip:map[addr:IPADDRESS type:V4] location:map[source:GSLB_LOCATION_SRC_INHERIT_FROM_SITE] ratio:1]] name:POOLNAME priority:10]] health_monitor_refs:[https://xxxxxxxxxxx] health_monitor_scope:GSLB_SERVICE_HEALTH_MONITOR_ALL_MEMBERS name:GSLBNAME num_dns_ip:1 tenant_ref:https://xxxxxxxxxxx ttl:30 url:https://xxxxxxxxxxxxxxx use_edns_client_subnet:true uuid:gslbservice-xxxxxxxxxxxx wildcard_match:false]
I am able to access
name
anddomain_names
,assert.Equal(t, gslbmap["name"], "GSLBNAME") assert.Equal(t, gslbmap["domain_names"], []interface {}([]interface {}{"GSLBNAME"}))
Now I am trying to access fields such as algorithm, fqdn which are inside a map list (or is it an array?) (
groups
)Any assistance,
-
pyhamcrest matcher for list fails
I have in my code the following test function:
from hamcrest import assert_that, contains_inanyorder, has_entries def test_associate_multiple_agents_to_skill(agent1, agent2, skill): with a.agent_skill(agent1, skill): response = confd.agents(agent2['id']).skills(skill['id']).put() response.assert_updated() response = confd.agents.skills(skill['id']).get() logger.critical(response) logger.critical(response.item) assert_that( response.item, has_entries( agents=contains_inanyorder( has_entries(id=agent1['id']), has_entries(id=agent2['id']) ) ), )
which gives me the following AssertionError:
AssertionError: Expected: a dictionary containing {'agents': a sequence over [a dictionary containing {'id': <8>}, a dictionary containing {'id': <9>}] in any order} but: value for 'agents' not matched: <[{'id': 8, 'number': '6977', 'firstname': None, 'lastname': None, 'links': [{'rel': 'agents', 'href': 'http://127.0.0.1:49462/1.1/agents/8'}]}]>
and the output of the
logger.critical
that I did in the function's code to check the response is:<Response 200 {'agents': [ [{'firstname': None, 'id': 8, 'lastname': None, 'links': [{'href': 'http://127.0.0.1:49404/1.1/agents/8', 'rel': 'agents'}], 'number': '6481'}], [{'firstname': None, 'id': 9, 'lastname': None, 'links': [{'href': 'http://127.0.0.1:49404/1.1/agents/9', 'rel': 'agents'}], 'number': '9741'}]], 'category': None, 'description': None, 'id': 8, 'links': [{'href': 'http://127.0.0.1:49404/1.1/agents/skills/8', 'rel': 'skills'}], 'name': 'iKZJOZDEfc', 'tenant_uuid': 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeee1'} >
and the output for response.item is:
{'id': 8, 'tenant_uuid': 'eeeeeeee-eeee-eeee-eeee-eeeeeeeeeee1', 'name': 'iKZJOZDEfc', 'category': None, 'description': None, 'links': [{'rel': 'skills', 'href': 'http://127.0.0.1:49404/1.1/agents/skills/8'}], 'agents': [ [ {'id': 8, 'number': '6481', 'firstname': None, 'lastname': None, 'links': [{'rel': 'agents', 'href': 'http://127.0.0.1:49404/1.1/agents/8'}]}], [{'id': 9, 'number': '9741', 'firstname': None, 'lastname': None, 'links': [{'rel': 'agents', 'href': 'http://127.0.0.1:49404/1.1/agents/9'}]}]]}
I have tried to change the function into the following but stil; it did not work:
def test_associate_multiple_agents_to_skill(agent1, agent2, skill): with a.agent_skill(agent1, skill): response = confd.agents(agent2['id']).skills(skill['id']).put() response.assert_updated() response = confd.agents.skills(skill['id']).get() logger.critical(response) logger.critical(response.item) assert_that( response.item, has_entries( agents=has_items( contains_inanyorder( has_entries(id=agent1['id']), ), contains_inanyorder( has_entries(id=agent2['id']), ), ), ), )
Any suggestions to make the assertion work?
-
Marshmallow ValidationError 'field_name' issue
I have one question concerning newer versions of Marhsmallow API. In our project we are currently using Marshmallow version 3.0.0b14; and we have the following tests functions defined (work perfectly):
from marshmallow.exceptions import ValidationError from hamcrest import assert_that, calling, has_properties, has_item, not_ def test_invalid_expiration(self): invalid_values = [None, True, False, 'foobar', 0] for value in invalid_values: body = {'expiration': value} assert_that( calling(self.schema.load).with_args(body), raises(ValidationError).matching( has_properties(field_names=has_item('expiration')) ), ) def test_that_acces_type_offline_requires_a_client_id(self): body = {'access_type': 'offline'} assert_that( calling(self.schema.load).with_args(body), raises(ValidationError).matching( has_properties(field_names=has_item('_schema')) ), ) def test_that_the_access_type_is_online_when_using_a_refresh_token(self): body = {'refresh_token': 'foobar', 'client_id': 'x'} assert_that(calling(self.schema.load).with_args(body), not_(raises(Exception))) assert_that( calling(self.schema.load).with_args({'access_type': 'online', **body}), not_(raises(Exception)), ) assert_that( calling(self.schema.load).with_args({'access_type': 'offline', **body}), raises(ValidationError).matching( has_properties(field_names=has_item('_schema')) ), ) def test_that_a_refresh_token_requires_a_client_id(self): body = {'refresh_token': 'the-token'} assert_that( calling(self.schema.load).with_args({'client_id': 'x', **body}), not_(raises(Exception)), ) assert_that( calling(self.schema.load).with_args(body), raises(ValidationError).matching( has_properties(field_names=has_item('_schema')) ), )
Now, we are trying to bump the version of Marshmallow in order to upgrade it to 3.10.0; however, in this version,
field_names
fromValidationError
has been removed and replaced byfield_name
(which is always equal to_schema
if i am correct).So my question is the following: how can we change/modify the tests posted above so that we don't have any error when executing them. This is what I have tried so far:
raises(ValidationError).matching( has_properties(messages=has_item('expiration')) ), raises(ValidationError).matching( has_properties(messages=has_item('_schema')) ),
We did not match on the new
field_name
since it is always equal to_schema
; so we went on matching/probing themessages
field; the following issue relates to a similar issue to what we are facing: