cumulocity-cypress
Version:
Cypress commands for Cumulocity IoT
59 lines (58 loc) • 2.22 kB
JavaScript
import { getAuthOptions, resetClient, userAliasFromArgs, getAuthOptionsFromCypressEnv, } from "../utils";
import { isAuthOptions, } from "../../shared/auth";
export { isAuthOptions, getAuthOptionsFromCypressEnv, getAuthEnvVariables, };
const getAuthEnvVariables = () => {
const env = Cypress.env();
const filteredKeysAndValues = {};
Object.keys(env).forEach((key) => {
if (key.endsWith("_username") ||
key.endsWith("_password") ||
key.endsWith("_token") ||
key === "C8Y_USERNAME" ||
key === "C8Y_USER" ||
key === "C8Y_PASSWORD" ||
key === "C8Y_TOKEN" ||
key === "C8Y_XSRF_TOKEN" ||
key === "C8Y_AUTHORIZATION") {
filteredKeysAndValues[key] = env[key];
}
});
return filteredKeysAndValues;
};
Cypress.Commands.add("getAuth", { prevSubject: "optional" }, (...args) => {
const auth = authFn("getAuth", args);
return cy.wrap(auth, { log: false });
});
Cypress.Commands.add("useAuth", { prevSubject: "optional" }, (...args) => {
const auth = authFn("useAuth", args);
if (auth != null) {
const win = cy.state("window");
win.localStorage.setItem("__auth", JSON.stringify(auth));
}
resetClient();
return cy.wrap(auth, { log: false });
});
function authFn(fnName, args) {
const auth = getAuthOptions(...args);
const userAlias = userAliasFromArgs(...args);
const consoleProps = {
getauthoptions: auth || null,
arguments: args || null,
env: getAuthEnvVariables() || null,
userAlias: userAlias || null,
};
const logger = Cypress.log({
name: fnName,
message: `${auth?.userAlias ? auth.userAlias + " -> " : ""}${auth ? auth.user : ""}`,
consoleProps: () => consoleProps,
autoEnd: false,
});
if (auth == null && userAlias != null) {
logger.end();
throw new Error(`No authentication found for userAlias ${userAlias}. Configure authentication ` +
`using ${userAlias}_token or ${userAlias}_username and ${userAlias}_password environment variables.`);
}
consoleProps.Yields = auth || null;
logger.end();
return auth;
}