Travis-CI tests Failing - django-rest-framework

I have an endpoint I built with Djangorestframework that takes in a picture as part of the request payload. Now, I am testing that endpoint using pytest and everything works fine locally, but the moment I push to github and my travis-ci tries to run the test, I get an error with not much information as to what is going on. It is also worth noting that that is the only endpoint that is failing on travis-ci. The code snippet of my test is below and I will also attach an image of the error on travis-ci
#pytest.mark.django_db
class TestCreateItem:
def test_successful_item_creation(self, client, seller_token):
"""
Test for successful item creation
GIVEN: A seller enters name, price, image and description of items
WHEN: The seller submits the form
THEN: They should get a success response of status code 201, A message that says 'Item has been created successfully'
"""
with open('tests/test_item/0_U8TbUaajSO7rXk1j.jpg', 'rb') as image:
data = {
"name": "An Item",
"price": 15000.55,
"description": "This is a random item",
"image": image
}
response = client.post("/items/create_item", data=data, **seller_token)
response_data = response.json()
print(response_data)
assert response.status_code == 201
assert response_data["message"] == "Item has been created successfully"

Related

google analytics GA4 API integration in RAILS 5.2 using google-apis-analyticsdata_v1beta gem library

I'm getting an error in request invalid
`gem 'google-apis-analyticsdata_v1beta', '~> 0.21.0'
# Load the client
require "google/apis/analyticsdata_v1beta"
require 'googleauth'
namespace :google_analytics do
desc 'cron job for syncing google analytics services'
task :analytics => [:environment] do
begin
client = Google::Apis::AnalyticsdataV1beta::AnalyticsDataService.new
credentials = Google::Auth::ServiceAccountCredentials.make_creds(json_key_io: IO.new(IO.sysopen('credentials.json')))
credentials.scope = 'https://www.googleapis.com/auth/analytics.readonly'
client.authorization = credentials.fetch_access_token!({})["access_token"]
body = {
"requests": [
{
"date_ranges": [
{
"start_date": "7daysAgo",
"end_date": "today"
}
],
"dimensions": [
{
"name": "pageTitle"
}
]
}
]
}
request = Google::Apis::AnalyticsdataV1beta::BatchRunReportsRequest.new(body)
property_id = '3384098947333'
property = "properties/#{property_id}"
results = client.batch_property_run_reports(property, request)
pp results
rescue => exception
puts "Exception : Error"
puts exception.message
puts "------------------------------"
end
end
end
i have tried gem 'google-apis-analyticsdata_v1beta' which help us to send API along with authorisation
I have created custom user field with custom event so i can get that data back for showing report in my so using API for the same but getting error in request, what exactly syntax for the same not sure, lack of documentation won't be able to do it well, if anyone help that would be great
creating job so that will run every periodically and fetch data to my app from google analytics

Kubernetes Pods Restart Notification alerts on my team's channel

My Pods are running on AKS Cluster. Whenever my pods restarted, I had to get a notification on my team's channel, are there any articles or commands to configure the notification?
For that same, you can use tools or application like botkube : https://www.botkube.io/
Also check the Kubewatch : https://github.com/bitnami-labs/kubewatch
You can also implement the Grafana with the Prometheus and Alert manager for monitoring and getting the alert system. : https://github.com/grafana-operator/grafana-operator
However if you can not looking for any tools or applications you can write down the custom script of python, node or any language you are good with and monitor any pod restart event and send the slack hook event.
Sharing one example python code with check the POD running or crashing and send a notification to slack you can update the logic as per need.
from kubernetes import client, config, watch
import json
import requests
import time
logger = logging.getLogger('k8s_events')
logger.setLevel(logging.DEBUG)
# If running inside pod
#config.load_incluster_config()
# If running locally
config.load_kube_config()
v1 = client.CoreV1Api()
v1ext = client.ExtensionsV1beta1Api()
w = watch.Watch()
mydict={}
webhook_url = '';
while True:
pod_list= v1.list_namespaced_pod("default");
for i in pod_list.items:
for c in i.status.container_statuses:
if(c.ready == True):
if i.metadata.name in mydict:
print("Inside mydict If");
print("Pod updated : ",i.metadata.name);
print("My dict value : ",mydict);
mydict[i.metadata.name]['end_time'] = i.status.conditions[1].last_transition_time;
dt_started = mydict[i.metadata.name]['start_time'].replace(tzinfo=None);
dt_ended = mydict[i.metadata.name]['end_time'].replace(tzinfo=None);
duration = str((dt_ended - dt_started).total_seconds()) + ' Sec';
fields = [{"title": "Status", "value": "READY", "short": False }, {"title": "Pod name", "value": i.metadata.name, "short": False }, {"title": "Duration", "value": duration, "short": False }, {"title": "Service name", "value": c.name, "short": False } ]
if c.name not in ('conversation-auto-close-service-scheduler','admin-service-trail-fllow-up-scheduler','bot-trial-email-scheduler','conversation-service-scheduler','faq-service-scheduler','nlp-service-scheduler','refresh-add-on-scheduler','response-sheet-scheduler'):
text = c.name + " Pod is started";
data = {"text": text, "mrkdwn": True, "attachments" : [{"color": "#FBBC05", "title": "Pod Details", "fields" : fields, "footer": "Manvar", "footer_icon": "https://cdn.test.manvar.com/assets/manvar-icon.png"}, ], }
print("Final data to post: ",data);
response = requests.post(webhook_url, data=json.dumps(data),headers={'Content-Type': 'application/json'});
del mydict[i.metadata.name]
if response.status_code != 200:
raise ValueError('Request to slack returned an error %s, the response is:\n%s' % (response.status_code, response.text));
time.sleep(1);
else:
mydict[i.metadata.name] = {"start_time": i.status.conditions[0].last_transition_time,"end_time": i.status.conditions[1].last_transition_time};
I tried out Botkube but I did not want to publicly expose my cluster endpoint, so I wrote the following script based on the code from #Harsh Manvar. You can connect this to Teams using the Incoming Webhook Teams app from Microsoft.
from kubernetes import client, config
import json
import requests
import time
def monitorNamespace(namespace: str, webhookUrl: str):
v1 = client.CoreV1Api()
pod_list= v1.list_namespaced_pod(namespace);
podsNotRunning = {"Namespace": namespace, "Pods": []}
for pod in pod_list.items:
status = getPodStatus(pod)
if status != "Running":
podsNotRunning["Pods"].append({"Podname": pod.metadata.name, "status": status})
if len(podsNotRunning)>0:
sendAlert(podsNotRunning, webhookUrl)
def sendAlert(podsNotRunning, webhookUrl):
print(podsNotRunning)
response = requests.post(webhookUrl, data=json.dumps(podsNotRunning),headers={'Content-Type': 'application/json'});
if response.status_code != 200:
print('Response error:', response)
def getPodStatus(pod: client.models.v1_pod.V1Pod) -> str:
status = pod.status.phase
containerStatus = pod.status.container_statuses[0]
if containerStatus.started is False or containerStatus.ready is False:
waitingState = containerStatus.state.waiting
if waitingState.message is not None:
status = waitingState.reason
return status
if __name__ == "__main__":
# If running inside pod:
#config.load_incluster_config()
# If running locally:
config.load_kube_config()
webhookUrl = 'http://webhookurl'
namespace='default
interval = 10
while True:
monitorNamespace(namespace, webhookUrl)
time.sleep(interval)

cannot load URL (HTML page) using task module for microsoft teams app (node js)

I am trying to show a popup message to user using the task module. I have sent a attachment with type invoke. Here is the code
content.sendActivity(MessageFactory.attachment(CardFactory.heroCard('Task Module Invocation from Hero Card',
'This is a hero card with a Task Module Action button',
null, // No images
[{ type: 'invoke', title: 'Task Module', value: { type: 'task/fetch' } }])));
When I click on the Button I have received a request to my messaging end point and the response I have sent is
reply({
task: {
type: 'continue',
value: {
"title": "Task module title",
"height": 'large',
"width": 'large',
"url": "https://67aa9b57.ngrok.io/api/internal/teams/tabs/content",
"fallbackUrl": "https://67aa9b57.ngrok.io/api/internal/teams/tabs/content"
}
}
});
But in the popup message is blank. My ngrok url is not even being hit for the HTML page. This is what I see in popup. But the title was updated. I have no idea why it is not working.
Ant help would be thankful
This is pretty much always caused by the domain of the page not being listed in the valid domains for the application (you set this in your manifest json file, inside App Studio if you're using it). Because you've not listed this as a valid and "safe" domain, Teams won't even make any call at all, that's why there's nothing visible in the NGrok log even.
Just to be clear, we're talking about this section of the schema.

Upload image with RSpec has unexpected class on controller

I'm in trouble with RSpec and fixture_file_upload on post request.
Here's the problem: I'm trying to send an image by upload to create a category with image, but when the image arrives, it changes it's class type.
I'm waiting to get in params[:category][:image] an ActionDispatch::Http::UploadedFile but what I receive is ActionController::Parameters.
My request example:
context 'when creates a new main category with valid params' do
let(:category) do
{ category: { name: 'Bolos E bolos',
description: 'São bolos sim',
locale: 'pt-BR',
image: fixture_file_upload('images/test-image.png', 'image/png') } }
end
post '/v4/categories' do
it 'upload image' do
expect { do_request(category) }.to change { ActiveStorage::Blob.count }.from(0).to(1)
end
end
end
what I got:
Failure/Error: expect { do_request(category) }.to change { ActiveStorage::Blob.count }.by(1)
expected `ActiveStorage::Blob.count` to have changed by 1, but was changed by 0
How do I send the image as upload and get it on the controller as ActionDispatch::Http::UploadedFile instead ActionController::Parameters
I could not get your controller spec working, but I managed to get an equivalent request spec working. Having spent 45+ minutes getting no where, I think this is the best I can do. This seems to work. (Just make sure you have an avatar.jpg in the public folder of your rails app.)
## spec/requests/user_spec.rb
require 'rails_helper'
RSpec.describe "Users", type: :request do
describe "it attaches uploaded files" do
it 'attaches the uploaded file' do
file = fixture_file_upload(Rails.root.join('public', 'avatar.jpg'), 'image/jpg')
expect {
post api_users_path, params: { user: {username: "Ben", avatar: file } }
}.to change(ActiveStorage::Attachment, :count).by(1)
end
end
end

Kony service giving 1012 opstatus Request failed error and not giving response

I have a kony sample app where I am trying to do a build and the app has one web service in it for fetching categories of some product. I have the following code also that I wrote:
function GetCategories() {
var inputparam = {
"appID": "bbuy",
"serviceID": "GetCategories",
"catId": "cat00000",
"channel": "rc",
"httpheaders": {}
};
kony.net.invokeServiceAsync("http://192.168.42.134/middleware/MWservlet",inputparam, serv_GetCategoriesCallback);
}
I am getting no response for this. Getting 1012 opstatus and the message is saying "Request failed" error.
kony.net.invokeServiceAsync("http://192.168.42.134/middleware/MWservlet",inputparam, serv_GetCategoriesCallback);
In the above line, you have not given the port number in the MWservlet URL.(e.g. 8080) Give that and check.
Also, make sure all input params are being fed to the service and that they correspond to the exact naming convention followed in the service editor.
Visit :
Find the below link. i hope it gives you a solution
http://developer.kony.com/twiki/pub/Portal/Docs/API_Reference/Content/Network_APIs.htm#net.invo2
Check the mandatory and optional fields of Inputparam

Resources