Merge pull request #6 from amunaadh/APItest_branch

API test added for addUsers
This commit is contained in:
Yamuna Adhikari 2020-10-14 13:04:27 +05:45 committed by GitHub
commit f46c0de35e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 268 additions and 110 deletions

View File

@ -5,7 +5,7 @@
"nightwatch-api": "^3.0.1" "nightwatch-api": "^3.0.1"
}, },
"scripts": { "scripts": {
"test:e2e": "node_modules/cucumber/bin/cucumber-js --require test/acceptance/index.js --require test/acceptance/stepDefinitions -f node_modules/cucumber-pretty" "test:e2e": "node_modules/cucumber/bin/cucumber-js --require test/acceptance/index.js --require test/acceptance/setup.js --require test/acceptance/stepDefinitions -f node_modules/cucumber-pretty"
}, },
"dependencies": { "dependencies": {
"cucumber-pretty": "^6.0.0", "cucumber-pretty": "^6.0.0",

View File

@ -0,0 +1,67 @@
Feature: Add user
As an admin
I want to add users
So that the authorized access is possible
Scenario: Admin adds user without permission
Given the user with login "harrypotter@gmail.com" does not exist
When the admin creates user with following details using API
| last name | Potter |
| login | harrypotter@gmail.com |
| password | password |
Then the response status code should be "200"
And user with login "harrypotter@gmail.com" should exist
Scenario: Admin creates already existing user
Given the admin has created the following users
| login | last name | password |
| Harry | Potter | hello123 |
When the admin creates user with following details using API
| last name | Potter |
| login | Harry |
| password | hello123 |
Then the response status code should be "500"
And the response message should be "ErrorLoginAlreadyExists"
Scenario Outline: Admin adds user with incomplete essential credentials
Given the user with login "Harry" does not exist
When the admin creates user with following details using API
| last name | <last name> |
| login | Harry |
| password | <password> |
Then the response status code should be "200"
And user with login "Harry" should exist
Examples:
| last name | password |
| | |
| Manson | |
| | 123 |
Scenario Outline: Admin adds user without login
Given the user with login "harrypotter@gmail.com" does not exist
When the admin creates user with following details using API
| last name | <last name> |
| login | |
| password | <password> |
Then the response status code should be "500"
And the response message should be "Field 'Login' is required"
Examples:
| last name | password |
| Potter | Hello123 |
| Potter | |
| | hello123 |
Scenario Outline: Admin adds user with last name as special characters
Given the user with login "<login>" does not exist
When the admin creates user with following details using API
| last name | <last name> |
| login | <login> |
| password | password |
Then the response status code should be "200"
And user with login "<login>" should exist
Examples:
| last name | login |
| swi@ | s$5^2 |
| g!!@%ui | |
| swikriti@h | ि $%#?&@name.txt |
| !@#$%^&*()-_+ | España§àôœ€ |

View File

@ -30,7 +30,7 @@ module.exports = {
elements: { elements: {
userRow: { userRow: {
selector: '//table[contains(@class,"tagtable liste")]/tbody/tr[position()>2]', selector: '//table[contains(@class,"tagtable")]/tbody/tr[position()>2]',
locateStrategy: 'xpath' locateStrategy: 'xpath'
}, },
@ -40,7 +40,7 @@ module.exports = {
}, },
userList: { userList: {
selector: '//table[contains(@class,"tagtable liste")]/tbody/tr[position()>2]/td/a//span[normalize-space(@class="nopadding usertext")][.="%s"]/../../following-sibling::td[.="%s"]', selector: '//table[contains(@class,"tagtable")]/tbody/tr[position()>2]/td/a//span[normalize-space(@class="nopadding usertext")][.="%s"]/../../following-sibling::td[.="%s"]',
locateStrategy: 'xpath' locateStrategy: 'xpath'
} }
} }

77
test/acceptance/setup.js Normal file
View File

@ -0,0 +1,77 @@
const { Before, After } = require('cucumber');
const { client } = require('nightwatch-api');
const fetch = require('node-fetch');
let initialUsers = {};
let dolApiKey = '';
const getUsers = async function () {
const header = {};
const url = client.globals.backend_url + 'api/index.php/users';
const users = {};
header['Accept'] = 'application/json';
header['DOLAPIKEY'] = dolApiKey;
await fetch(url, {
method: 'GET',
headers: header
})
.then(async (response) => {
const json_response = await response.json();
for (const user of json_response) {
users[user.id] = user.id;
}
});
return users;
};
Before(async function getDolApiKey() {
const header = {}
const adminUsername = client.globals.adminUsername;
const adminPassword = client.globals.adminPassword;
const params = new URLSearchParams()
params.set('login', adminUsername)
params.set('password', adminPassword)
const apiKey = `http://localhost/dolibarr/htdocs/api/index.php/login?${params.toString()}`;
header['Accept'] = 'application/json'
await fetch(apiKey, {
method: 'GET',
headers: header
})
.then(async (response) => {
const jsonResponse = await response.json()
dolApiKey = jsonResponse['success']['token']
client.globals.dolApiKey = dolApiKey
})
})
Before(async () => {
initialUsers = await getUsers();
});
After(async () => {
const finalUsers = await getUsers();
const header = {};
const url = client.globals.backend_url + 'api/index.php/users/';
header['Accept'] = 'application/json';
header['DOLAPIKEY'] = dolApiKey;
let found;
for (const finaluser in finalUsers) {
for (const initialuser in initialUsers) {
found = false;
if (initialuser === finaluser) {
found = true;
break;
}
}
if (!found) {
await fetch(url + finaluser, {
method: 'DELETE',
headers: header
})
.then(res => {
if (res.status < 200 || res.status >= 400) {
throw new Error("Failed to delete user: " + res.statusText);
}
});
}
}
});

View File

@ -1,142 +1,156 @@
const { Before, Given, When, Then, After } = require('cucumber'); const {Given, When, Then} = require('cucumber');
const { client } = require('nightwatch-api'); const {client} = require('nightwatch-api');
const fetch = require('node-fetch'); const fetch = require('node-fetch');
let initialUsers = {}; const assert = require('assert');
let dolApiKey = ''; let response;
let Login = {};
Given('the administrator has logged in using the webUI', async function () { Given('the administrator has logged in using the webUI', async function () {
await client.page.loginPage().navigate().waitForLoginPage(); await client.page.loginPage().navigate().waitForLoginPage();
await client.page.loginPage().userLogsInWithUsernameAndPassword(client.globals.adminUsername, client.globals.adminPassword); await client.page.loginPage().userLogsInWithUsernameAndPassword(client.globals.adminUsername, client.globals.adminPassword);
return client.page.loginPage().userIsLoggedIn(client.globals.adminUsername); return client.page.loginPage().userIsLoggedIn(client.globals.adminUsername);
}); });
Given('the administrator has browsed to the new users page', function () { Given('the administrator has browsed to the new users page', function () {
return client.page.homePage().browsedToNewUserPage(); return client.page.homePage().browsedToNewUserPage();
}); });
When('the admin creates user with following details', function (datatable) { When('the admin creates user with following details', function (datatable) {
return client.page.addUsersPage().adminCreatesUser(datatable); return client.page.addUsersPage().adminCreatesUser(datatable);
}); });
Then('new user {string} should be created', function (lastname) { Then('new user {string} should be created', function (lastname) {
return client.page.addUsersPage().newUserShouldBeCreated(lastname); return client.page.addUsersPage().newUserShouldBeCreated(lastname);
}); });
Then('message {string} should be displayed in the webUI', function (message) { Then('message {string} should be displayed in the webUI', function (message) {
return client.page.addUsersPage().noPermissionMessage(message); return client.page.addUsersPage().noPermissionMessage(message);
}); });
Then('message {string} should not be displayed in the webUI', function (message) { Then('message {string} should not be displayed in the webUI', function (message) {
return client.page.addUsersPage().noPermissionDefinedMessageNotShown(message); return client.page.addUsersPage().noPermissionDefinedMessageNotShown(message);
}); });
Then('new user {string} should not be created', function (lastname) { Then('new user {string} should not be created', function (lastname) {
return client.page.addUsersPage().userNotCreated(lastname); return client.page.addUsersPage().userNotCreated(lastname);
}); });
Given('a user has been created with following details', function (dataTable) { Given('a user has been created with following details', function (dataTable) {
return adminHasCreatedUser(dataTable); return adminHasCreatedUser(dataTable);
}); });
Given('the admin has created the following users', function (dataTable) { Given('the admin has created the following users', function (dataTable) {
return adminHasCreatedUser(dataTable); return adminHasCreatedUser(dataTable);
}); });
const getUsers = async function () { When('the admin creates user with following details using API', function (dataTable) {
const header = {}; return adminCreatesUserWithAPI(dataTable);
const url = client.globals.backend_url + 'api/index.php/users'; });
const users = {};
header['Accept'] = 'application/json'; Given('the user with login {string} does not exist', async function (login) {
header['DOLAPIKEY'] = dolApiKey; await userDoesNotExist(login);
await fetch(url, { });
method: 'GET',
headers: header Then('the response status code should be {string}', function (expectedStatusCode) {
}) return getStatusCode(expectedStatusCode);
.then(async (response) => { });
const json_response = await response.json();
for (const user of json_response) { Then('user with login {string} should exist', function (login) {
users[user.id] = user.id; return userShouldExist(login);
} });
});
return users; Then('the response message should be {string}', function (expectedResponseMessage) {
return getResponseMessage(expectedResponseMessage);
});
const createUserRequest = function (login, lastname, password) {
const header = {};
const url = client.globals.backend_url + 'api/index.php/users';
header['Accept'] = 'application/json';
header['DOLAPIKEY'] = client.globals.dolApiKey;
header['Content-Type'] = 'application/json';
return fetch(url, {
method: 'POST',
headers: header,
body: JSON.stringify(
{
login: login,
lastname: lastname,
pass: password
}
)
});
};
const adminCreatesUserWithAPI = function (dataTable) {
const userDetails = dataTable.rowsHash();
return createUserRequest(userDetails['login'], userDetails['last name'], userDetails['password'])
.then((res) => {
response = res;
});
}; };
const adminHasCreatedUser = async function (dataTable) { const adminHasCreatedUser = async function (dataTable) {
const header = {}; const userDetails = dataTable.hashes();
const url = client.globals.backend_url + 'api/index.php/users'; for (const user of userDetails) {
header['Accept'] = 'application/json'; await createUserRequest(user['login'], user['last name'], user['password'])
header['DOLAPIKEY'] = dolApiKey; .then((response) => {
header['Content-Type'] = 'application/json'; if (response.status < 200 || response.status >= 400) {
const userDetails = dataTable.hashes(); throw new Error('Failed to create user: ' + user['login'] +
for (const user of userDetails) { ' ' + response.statusText);
await fetch(url, { }
method: 'POST', });
headers: header, }
body: JSON.stringify(
{
login: user['login'],
lastname: user['last name'],
pass: user['password']
}
)
})
.then((response) => {
if (response.status < 200 || response.status >= 400) {
throw new Error('Failed to create user: ' + user['login'] +
' ' + response.statusText);
}
return response.text();
});
}
}; };
Before(async () => { const getUsersLogin = async function () {
const header = {} const header = {};
const adminUsername = client.globals.adminUsername; const url = client.globals.backend_url + 'api/index.php/users/';
const adminPassword = client.globals.adminPassword; header['Accept'] = 'application/json';
const params = new URLSearchParams() header['DOLAPIKEY'] = client.globals.dolApiKey;
params.set('login', adminUsername) header['Content-Type'] = 'application/json';
params.set('password', adminPassword) await fetch(url, {
const apiKey = `http://localhost/dolibarr/htdocs/api/index.php/login?${params.toString()}`; method: 'GET',
header['Accept'] = 'application/json' headers: header
await fetch(apiKey, { })
method: 'GET', .then(async (response) => {
headers: header const json_response = await response.json();
}) for (const user of json_response) {
.then(async (response) => { Login[user.login] = user.login;
const jsonResponse = await response.json() }
dolApiKey = jsonResponse['success']['token'] });
}) };
})
Before(async () => {
initialUsers = await getUsers();
});
After(async () => { const userDoesNotExist = async function (login) {
const finalUsers = await getUsers(); await getUsersLogin();
const header = {}; if (login in Login) {
const url = client.globals.backend_url + 'api/index.php/users/'; Login = {};
header['Accept'] = 'application/json'; throw new Error(`user ${login} exists`);
header['DOLAPIKEY'] = dolApiKey; }
let found; Login = {};
for (const finaluser in finalUsers) { return;
for (const initialuser in initialUsers) { };
found = false;
if (initialuser === finaluser) { const userShouldExist = async function (login) {
found = true; await getUsersLogin();
break; if (login in Login) {
} Login = {};
} return;
if (!found) { } else {
await fetch(url + finaluser, { Login = {};
method: 'DELETE', throw new Error(`User ${login} does not Exist`);
headers: header }
}) };
.then(res => {
if (res.status < 200 || res.status >= 400) { const getStatusCode = async function (expectedStatusCode) {
throw new Error("Failed to delete user: " + res.statusText); const actualStatusCode = response.status.toString();
} return assert.strictEqual(actualStatusCode, expectedStatusCode,
}); `The expected status code was ${expectedStatusCode} but got ${actualStatusCode}`);
} };
}
}); const getResponseMessage = async function (expectedResponseMessage) {
const json_response = await response.json();
const actualResponseMessage = json_response['error']['0'];
return assert.strictEqual(actualResponseMessage, expectedResponseMessage,
`the expected response message was ${expectedResponseMessage} but got ${actualResponseMessage}`);
};