How to print value with assert in python - python-3.x

I am new to python and trying to print value with assert function in python.
Below is example code:
HEADERS_VALID = {'Content-Type': 'application/json', 'fiware-Service': 'test', 'fiware-ServicePath': '/t1'}
HEADERS_INVALID = {'Content-Type': 'application/json', 'fiwareService': 'test', 'fiwareServicePath': '/t1'}
def test_for_valid_headers(notification):
notification['data'][0] = {
'id': 'Room0',
'type': 'Room',
'temperature': {'type': 'Number', 'value': '100', 'metadata': {'dateModified': {'type': 'DateTime','value': '1980-01-30T00:00:00.000+00:00'}}},
'pressure': {'type': 'Number', 'value': '10', 'metadata': {'dateModified': {'type': 'DateTime','value': '1980-01-30T00:00:00.000+00:00'}}},
}
res_post = requests.post(data=json.dumps(notification),
headers=HEADERS_VALID)
time.sleep(1)
assert res_post.status_code == 200
assert res_post.json() == 'Notification successfully processed'
get_url = "{}/entities/Room0".format(QL_URL)
res_get = requests.get(get_url, headers=HEADERS_VALID)
assert res_get.status_code == 200
exp_values = {
"attributes": [{'attrName': 'pressure', 'values': [10.0]}, {'attrName':
'temperature', 'values': [100.0]}],
"entityId": 'Room0',
"index": [
'1980-01-30T00:00:00.000+00:00'
]
}
assert res_get.json() == exp_values
Here in res_post.json() the actual response is "Notification successfully processed for : 'tenant' test, 'fiwareServicePath' /t1, 'entity_id' ['Room0']" which is not equal to 'Notification successfully processed' in assert function. So, want to add rest part in assert fucntion.
After this response i added ,
assert res_post.json() == "Notification successfully processed for: : 'tenant' %s, 'fiwareServicePath' %s" %(fiware_s, fiware_sp)
which is giving error as : NameError: name 'fiware' is not defined
I am not able to get what i am doing wrong in this statement.Any help on this will be great. Thanks in advance.

Related

Python Marshmallow AttributeError: 'list' object has no attribute 'get'

I have this schema
from marshmallow import validate, ValidationError
from marshmallow_jsonapi import fields
from marshmallow_jsonapi.flask import Relationship, Schema
class UserSchema(Schema):
first_name = fields.Str(required=True])
last_name = fields.Str(required=True)
title = fields.Str(required=True)
class Meta:
type_ = 'users'
self_view = "blog_view.users_detail"
self_view_kwargs = {"user_id": "<id>", "_external": True}
self_view_many = "blog_view.users_list"
blog= Relationship(
many=False,
include_data=True,
type_="blogs",
include_resource_linkage=True,
schema="BlogSchema"
)
I want to load this data(coming from UI) for validation:
bulk_data = [
{ 'type': 'users',
'relationships': {'blog': {'data': {'type': 'blogs', 'id': blog_id}}},
{'first_name': 'Billy', 'last_name': 'Butcher', 'title': 'Supe Hunter'}
},
{ 'type': 'users',
'relationships': {'blog': {'data': {'type': 'blogs', 'id': blog_id}}},
{'first_name': 'Home', 'last_name': 'Lander', 'title': 'Leader'}
},
{ 'type': 'users',
'relationships': {'blog': {'data': {'type': 'blogs', 'id': blog_id}}},
{'first_name': 'Black', 'last_name': 'Noir', 'title': 'Super Ninja'}
}
]
For validation I did:
data = UserSchema(many=True).load(input_data)
I get an error saying,
AttributeError: 'list' object has no attribute 'get'
which is obvious because I'm passing a list. The validation works fine when I pass a single dictionary from the above list, but I want to pass the bulk data and do validation at once as shown in Marshmallow doc: https://marshmallow.readthedocs.io/en/stable/quickstart.html#validation
When
many=True
, load method expects a collection type so list, tuple, queryset etc.
Any suggestion on how to validate a list of data in Marshmallow? The marshmallow versions are:
marshmallow==2.18.0
marshmallow-jsonapi==0.23.1
Thanks!

How to compare 2 lists of dictionnaries?

I'm trying to compare 2 lists of dictionaries.
Please find an example below.
list1 = [
{'code': '1111', 'description': 'Test'},
{'code': '2222', 'description': 'Hello World'},
{'code': '3333', 'description': 'Stack'},
{'code': '4444', 'description': 'Gozilla'},
]
list2 = [
{'code': '3333', 'description': 'Stack'},
{'code': '4444', 'description': 'Megatron'},
{'code': '5555', 'description': 'Winnie the Pooh'}
]
I am trying to :
If ['code'] from list2 exist in list1, and if ['description'] is different, place it in a new list "updates".
If ['code'] from list2 does not exist in list1, place it in a new list "new".
At the end the 2 new lists from my example should look like that :
updates = [
{'code': '4444', 'description': 'Megatron'}
]
new = [
{'code': '5555', 'description': 'Winnie the Pooh'}
]
Any ideas how I could achieve that ?
You can convert list1 to dict to make comparing codes easier:
list1 = [
{'code': '1111', 'description': 'Test'},
{'code': '2222', 'description': 'Hello World'},
{'code': '3333', 'description': 'Stack'},
{'code': '4444', 'description': 'Gozilla'},
]
list2 = [
{'code': '3333', 'description': 'Stack'},
{'code': '4444', 'description': 'Megatron'},
{'code': '5555', 'description': 'Winnie the Pooh'}
]
updates = []
new = []
tmp = {d['code']: d['description'] for d in list1}
for d in list2:
if d['code'] in tmp and d['description'] != tmp[d['code']]:
updates.append(d)
elif not d['code'] in tmp:
new.append(d)
print(updates)
print(new)
Prints:
[{'code': '4444', 'description': 'Megatron'}]
[{'code': '5555', 'description': 'Winnie the Pooh'}]
#Otherwise,for example 4444 in between of list1 and list2
new_list = []
if list1[3].get('code')==list2[1].get('code'):
new_list.append(list2[1])
print(new_list)

How to disable Adaptive Cards on clicking once?

I am using an adaptive card in MSTeams Bot and on clicking once I want to disable the Submit button to prevent the user from clicking it again as the backend is running for the button click event.
Adaptive Card code -
async specialRewards() {
const specialRewardCard = CardFactory.adaptiveCard({
'$schema': 'http://adaptivecards.io/schemas/adaptive-card.json',
'version': '1.2',
'type': 'AdaptiveCard',
'body': [
{
'type': 'TextBlock',
'text': "Hey there! \n\n",
'wrap': true,
},
{
'type': 'TextBlock',
'text': 'Your birthday🎂 :',
'weight': 'Bolder',
'wrap': true,
},
{
'type': 'Input.Date',
'id': 'birthday',
'placeholder': 'Enter a date',
'spacing': 'Padding',
},
{
'type': 'TextBlock',
'text': 'Your work anniversary🎉 :',
'weight': 'Bolder',
'wrap': true,
},
{
'type': 'Input.Date',
'id': 'anniversary',
'placeholder': 'Enter a date',
'spacing': 'Padding',
},
],
'actions': [
{
'type': 'Action.Submit',
'title': 'Submit',
'isPrimary': true,
},
],
});
return specialRewardCard;
}
This is how it is looking on MSTeams
I'm working on a similar scenario myself at the moment and I've found the updateActivity() function to work well.
// Update the adaptive card so it cannot be used again
async followUp() {
const card = CardFactory.heroCard(
'Your card results',
'<b>Birthday:</b> ' + birthday + '<br>' + '<b>Anniversary:</b> ' + anniversary,
null
);
card.id = step.context.activity.replyToId;
const message = MessageFactory.attachment(card);
message.id = step.context.activity.replyToId;
await step.context.updateActivity(message);
}

Not able to fetch the value of DiskSpaceUtilization Metric from the Cloudwatch with AWS Lambda

I am trying to get the Used Disk Space (Percent) for my EC2 instance from Cloudwatch with the help of a lambda function. It returns no value.
And when I try to specify the Filesystem and Mountpath it shows an error -
Parameter validation failed:\nUnknown parameter in MetricDataQueries[0].MetricStat.Metric.Dimensions[0]: \"Filesystem\", must be one of: Name, Value",
"errorType": "ParamValidationError"
Here is the full code.
import boto3
import datetime
def lambda_handler(event, context):
client = boto3.client('cloudwatch')
response = client.get_metric_data(
MetricDataQueries=[
{
'Id': 'd1',
'MetricStat': {
'Metric': {
'Namespace': 'cloudwatch',
'MetricName': 'DiskSpaceUtilization',
'Dimensions': [
{
'Name': 'InstanceId',
'Value': '*****************',
'Filesystem': '/****/****'
},
]
},
'Period': 300,
'Stat': 'Maximum',
'Unit': 'Percent'
},
'ReturnData': True
},
],
StartTime=datetime.datetime.utcnow() - datetime.timedelta(seconds=600),
EndTime=datetime.datetime.utcnow(),
ScanBy='TimestampDescending',
MaxDatapoints=60
)
return response
I expect the output as DiskSpaceUtilization - x%.
But currently the output is
"MetricDataResults": [
{
"Id": "d1",
"Label": "DiskSpaceUtilization",
"Timestamps": [],
"Values": [],
"StatusCode": "Complete"
}
],
Filesystem is a separate dimension, change this:
'Dimensions': [
{
'Name': 'InstanceId',
'Value': '*****************',
'Filesystem': '/****/****'
},
]
to this:
'Dimensions': [
{
'Name': 'InstanceId',
'Value': '*****************'
},
{
'Name': 'Filesystem',
'Value': '/****/****'
}
]
and see what you get then (there could be other issues after you fix this one).

Transform a list of dict to an simpler dict

I have list of dict like this:
[{
'attr': 'bla',
'status': '1',
'id': 'id1'
}, {
'attr': 'bla',
'status': '1',
'id': 'id2'
}, {
'attr': 'bli',
'status': '0',
'id': 'id1'
}, {
'attr': 'bli',
'status': '1',
'id': 'id2'
}]
I wan't to get a simpler results dict like this:
result = {
'bla' : True,
'bli' : False
}
If the two id have a 1 for an attr, the value will be True. else, it will False.
I've tried with
for elem in dict:
for key, value in enumerate(elem):
# ???
But i don't see how to do. I've alos tried something like
if all( val == '1' for val in list ):
# ..
Here you go:
dicts = [{
'attr': 'bla',
'status': '1',
'id': 'id1'
}, {
'attr': 'bla',
'status': '1',
'id': 'id2'
}, {
'attr': 'bli',
'status': '0',
'id': 'id1'
}, {
'attr': 'bli',
'status': '1',
'id': 'id2'
}]
# First run is to create all nessecary items in the
# new Dictionary so i can use the and operator on them later.
newDict = {}
for dictio in dicts:
for key, value in dictio.items():
if key == 'attr':
newDict[value] = True
# The second run uses the and operator
for dictio in dicts:
for key, value in dictio.items():
if key == 'attr':
tmpAttr = value
if key == 'status':
newDict[tmpAttr] = newDict[tmpAttr] and (value == '1')
print(newDict)
Have a nice day!

Resources