how to create a loop in pyresttest? - pyresttest

I am trying to create a loop in PyRestTest, this is my code:
# Login
- test:
- group: 'Login'
- name: 'Test login post'
- url: {template: 'api/login/'}
- method: 'POST'
- body: {template:'{"username":"$username",
"email":"$username",
"password":"$password"}'}
- headers: {Content-Type: application/json}
- extract_binds:
- 'token': {'jsonpath_mini': "key"}
# Logout
- test:
- group: 'Logout'
- name: 'Test logout post'
- url: {template: 'api/logout/'}
- method: 'POST'
- headers: {Content-Type: application/json}
How can I execute this code over and over?. I am expecting something like:
loop(10):
# Login
...
# Logout
...
In order to execute 10 times these tests. Is it possible?

Related

Serverless framework WarmUp plugin not being called

I tried to integrate the WarmUp serverless plugin into my project. However, I believe that it is not working. I see no invocations from WarmUp in the lambda’s CloudWatch log group, and lambda does need warmup time after being idle for a bit.
My configuration is below:
service: ${file(./${env:DEPLOY_FILE_NAME}):service}
provider:
name: aws
custom:
roleName: ${file(./${env:DEPLOY_FILE_NAME_STAGE}):roleName}
profileName: ${file(./${env:DEPLOY_FILE_NAME_STAGE}):profileName}
bundle:
ignorePackages:
- pg-native
warmup:
enabled: true
events:
- schedule: rate(5 minutes)
prewarm: true
plugins:
- pluginHandler
- serverless-plugin-warmup
runtime: nodejs12.x
iamRoleStatements:
- Effect: 'Allow'
Action:
- 'lambda:InvokeFunction'
Resource:
- Fn::Join:
- ':'
- - arn:aws:lambda
- Ref: AWS::Region
- Ref: AWS::AccountId
- function:${self:service}-${opt:stage, self:provider.stage}-*
cfLogs: true
stage: ${file(./${env:DEPLOY_FILE_NAME_STAGE}):stage}
region: ${file(./${env:DEPLOY_FILE_NAME_STAGE}):region}
memorySize: ${file(./${env:DEPLOY_FILE_NAME_STAGE}):memorySize}
timeout: ${file(./${env:DEPLOY_FILE_NAME_STAGE}):timeout}
keepWarm: false
useApigateway: true
package:
exclude:
${file(./${env:DEPLOY_FILE_NAME}):exclude}
functions:
lambdaHandler:
handler: ${file(./${env:DEPLOY_FILE_NAME_STAGE}):handler}
events:
${file(./${env:DEPLOY_FILE_NAME}):events}
warmup:
enabled: true
The lambda code:
const awsLambdaFastify = require('aws-lambda-fastify');
const app = require('./index');
const proxy = awsLambdaFastify(app);
const fastify = (event, context, callback) => {
context.callbackWaitsForEmptyEventLoop = false;
proxy(event, context, callback);
};
const warm = func => (event, context, callback) => {
if (event.source === 'serverless-plugin-warmup') {
return callback(null, 'Lambda is warm!');
}
return func(event, context, callback);
};
exports.handler = warm(fastify);
Is there something that I could check? Any suggestions/directions are greatly appreciated.
Thank you
First of all, please move out the plugins from provider
plugins:
- serverless-plugin-warmup
provider:
...

I can't access $auth.user from auth plugin or middleware using nuxtjs and getting api from laravel

My goal is that i want to access $auth.user.roles from plugin and middleware to be able to not let this role reach the other role page.
what is expected is that when console.log($auth.user) it gives me the user data (id,...) and when a console.log($auth.loggedIn)it gives me true.
My problem is that i can't access $auth.user from plugin and middleware to chieve that which $auth.user = null and $auth.loggedIn = false while im logged in.
here is my nuxt.config.js:
axios: {
baseURL: env.parsed.API_URL || 'http://localhost:3000/api',
debug:true},
auth: {
strategies: {
local: {
endpoints: {
login: {
url: '/auth/signin',
method: 'post',
propertyName: 'data.token'
},
user: {
url: '/auth/me',
method: 'get',
propertyName: 'data'
},
logout: {
url: '/auth/signout',
method: 'post'
},
tokenRequired: true,
tokenType: 'bearer',
globalToken: true,
autoFetchUser: true
},
},
},
redirect:false,
plugins: [ '~/plugins/roles.js' ]
},
here is my plugins/roles.js :
export default function ({app}) {
const username = app.$auth.user
if (!app.$auth.loggedIn) {
return console.log(username ,'roles plugin ', app.$auth.loggedIn)
}}
here is the res: null roles plugin false
the same result using this code:
export default function ({$auth}) {
const username = $auth.user
if (!app.$auth.loggedIn) {
return console.log(username ,'roles plugin', $auth.loggedIn)
}}
Ps:when i use $auth.user in my vue pages it gives me the whole user data (thats wonderfull)
I searched about this problem so i found common answers like :
*Change the user propertyName to false.
*reinstall node_modules.
but same result
Thank you every one <3

How to access the return value of a lambda in a another cloudformation resource?

GetClientId:
Type: "AWS::Lambda::Function"
Properties:
Handler: index.handler
Role: !GetAtt LambdaESCognitoRole.Arn
Code:
ZipFile: !Sub |
var AWS = require('aws-sdk');
const cognitoidentityserviceprovider = new AWS.CognitoIdentityServiceProvider();
var response = require('cfn-response');
var responseData = {};
exports.handler = async (event, context) => {
console.log(JSON.stringify(event, null, 2));
var params = {
UserPoolId: event.ResourceProperties.UserPoolId
};
await cognitoidentityserviceprovider.listUserPoolClients(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else {
console.log(data); // successful response
responseData = {'ClientId': data.UserPoolClients[0].ClientId};
}
}).promise();
response.send(event, context, response.SUCCESS, responseData);
return;
}
Runtime: nodejs8.10
CallGetClientId:
Type: 'Custom::CallGetClientId'
Version: 1.0
Properties:
ServiceToken: !GetAtt GetClientId.Arn
UserPoolId: !Ref CognitoUserPool
IdentityPoolRoleMapping:
Type: "AWS::Cognito::IdentityPoolRoleAttachment"
Properties:
IdentityPoolId: !Ref CognitoIdentityPool
Roles:
authenticated: !GetAtt AuthenticatedRole.Arn
unauthenticated: !GetAtt UnauthenticatedRole.Arn
RoleMappings:
"cognito-identity-provider":
IdentityProvider: !Join ['', [ !GetAtt CognitoUserPool.ProviderName, ':', !GetAtt CallGetClientId.ClientId ]] #Need to get the ClientID here
AmbiguousRoleResolution: Deny
Type: Rules
RulesConfiguration:
Rules:
- Claim: "custom:groups"
MatchType: "Contains"
RoleARN: !GetAtt AuthenticatedRole.Arn
Value: "user"
- Claim: "custom:groups"
MatchType: "Contains"
RoleARN: !GetAtt AuthenticatedAdminRole.Arn
Value: "admin"
I see two ways to resolve the issue.
One - use the cfnresponse.send(...responseData) parameter. See here: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-lambda-function-code-cfnresponsemodule.html#w2ab1c17c25c14b9c11
My example:
cfnresponse.send(event, context, cfnresponse.SUCCESS, responseData, responseData['ClientSecret'])
Once you returned data from Lambda, you can refer to it in CFN template with !GetAtt:
Value: !GetAtt HapiUserPoolClientPostProc.ClientSecret
Two - I use custom resources as a components "post-processor", i.e. create the resources, and update their parameters with a custom resource after. This order will be guaranteed by custom resource lambda input parameters (dependency).
My example was to feed in Cognito AppClient callback URLs from my ElasticBeanstalk WebApp. So I create both the UserPool AppClient and the EB webapp, then a post-processor custom resource lambda takes the URL from EB and updates the CallbackURL in Cognito.
Hope this helps.

Ruby Mechanize Login form submit error

require "mechanize"
a = Mechanize.new { |agent| agent.user_agent_alias = 'Mac Safari' }
a.get('http://erp.jecrcuniversity.edu.in:8084/jecrc_academia/') do |page|
page.form_with(name: "loginForm") do |f|
f.userId = ARGV[0]
f.password1 = ARGV[1]
end.submit
end
a.get('http://122.15.3.5:8084/jecrc_webguru/login.do') do |page|
pp page
end
I am trying to login and then redirect to the page but it keeps redirecting me the login page again. I have also tried to do this but i still have same problem.
# jecrc_form = page.form('loginForm')
# username_field = jecrc_form.field_with(:name => 'userId')
# username_field.value = ARGV[0];
# password_field = jecrc_form.field_with(:name => 'password1')
# password_field.value = ARGV[1]
# jecrc_form.click_button
Pretty Print of my form is:
{forms
#<Mechanize::Form
{name "loginForm"}
{method "POST"}
{action "/jecrc_academia/CommonLoginCheck.do
;sessionid=1EA144A84FA0B3845126723B95634B4F"}
{fields
[hidden:0x126d9e0 type: hidden name: currentTime value: ]
[text:0x126d88c type: text name: userId value: ]
[hidden:0x126d738 type: hidden name: password value: ]
[field:0x126d5e4 type: password name: password1 value: ]}
{radiobuttons}
{checkboxes}
{file_uploads}
{buttons [button:0x126d47c type: button name: value: Login]}>}>
Here's what the browser sends:
currentTime: MTQ5MTg3OTYzNDAwMA==
userId: foo
password: 37b51d194a7513e45b56f6524f2d51f2
password1: bar
The password looks like a md5 and the currentTime is a base64 of a timestamp (1491879634000 in this case).

SailsJS Session not stored in local MemoryStore

I am building a react (ES6) application with Webpack in SailsJS.
The problem I came across is that session is not properly handled or stored in Local Memory Store IF the action is triggered from the frontend
Setup:
// TestAPIController:
module.exports = {
create: function(req, res){
// TODO: Add user authentication piece
var user = {name: 'test user'};
req.session.user = user.name;
req.session.authenticated = true;
console.log('session:', req.session);
// req.session.save();
res.json(req.session);
},
echo: function(req, res){
console.log('session:', req.session);
return res.json({message:'got it'});
}
};
Policy:
TestAPIController: {
echo : 'sessionAuth'
}
Route:
'GET /TestAPI/create' : {
controller: 'TestAPIController',
action:'create'
},
'GET /TestAPI/echo' : {
controller: 'TestAPIController',
action:'echo'
},
Front End
onClickCreate(e){
fetch('/TestAPI/create').then( res => res.json());
}
onClickEcho(e){
fetch('/TestAPI/echo').then(res => res.json());
}
MarkUp
<li><a onClick={_this.onClickCreate}>Create Test</a></li>
<li><a onClick={_this.onClickEcho}>Echo Test</a></li>
Senario A
Click on Create Console Log: [CORRECT!]
Requested :: GET /TestAPI/create
session: Session {
cookie:
{ path: '/',
_expires: 2017-01-18T20:21:01.069Z,
originalMaxAge: 86400000,
httpOnly: true },
user: 'test user',
authenticated: true }
And Then click on Echo, Console Log: [WRONG!]
Requested :: GET /TestAPI/echo
verbose: Sending 403 ("Forbidden") response:
You are not permitted to perform this action.
Senario B
Now go to http://localhost:3000/TestAPI/create in the chrome browser's URL
Browser prints the return from the call. and Log:
Requested :: GET /TestAPI/create
session: Session {
cookie:
{ path: '/',
_expires: 2017-01-18T20:21:13.645Z,
originalMaxAge: 86400000,
httpOnly: true },
user: 'test user',
authenticated: true }
And then enter http://localhost:3000/TestAPI/echo in url address
Browser prints the return from the call [CORRECT!]
Requested :: GET /TestAPI/echo
session: Session {
cookie:
{ path: '/',
_expires: 2017-01-18T20:25:24.019Z,
originalMaxAge: 86400000,
httpOnly: true },
user: 'test user',
authenticated: true }
Maybe there is some fundamental principle I'm not following?
Or maybe there is a better way to control sessions?
Any help would be appreciated.
You have the solution here guys: https://github.com/balderdashy/sails/issues/3965

Resources