const fs = require("fs");
const path = require("path");
const OptParser = require("./opt_parser");
// Timeout applied to every wait in debug mode, where the execution is paused at breakpoints for as long as you like.
const DEBUG_TIMEOUT_MSEC = 24 * 60 * 60 * 1000;
/**
* this class have configuratin information.
*/
class Config {
static get CONFIG_FILE_PATH(){
return "config.json";
}
static get DEFAULT_CONFIG(){
return {
browser: "puppeteer",
scenarioDir: "test",
scenarioFile: undefined,
ignoreDir: "supports",
silentMode: false,
exitImmediately: false, // whether or not keep shows for browser window on failed
screenshotOnFailure: "failure.png", // file name to save a screenshot when a test fails.
fileDownloadDir: "downloads",
screenshotsDir: "screenshots",
width: 1024,
height: 768,
mocha: {
ui: "bdd",
bail: true,
reporter: "spec",
timeout: 5000,
slow: false,
},
assertion: {
ssimThreshold: 0.95,
diffThreshold: 0.3
},
slowMotion: 0, // msec. if over 0, wait this msec before each action. the mocha timeout is disabled while it is enabled
debug: false, // if true, run in debug mode: pause the scenario and show DevTools on another browser.
debugPort: 9229, // port of the V8 inspector opened in debug mode
autoWaiting: {
enabled: true, // actions (such as click, fillIn, ...) wait until the element is actionable
timeout: 5000, // msec. give up waiting after this
interval: 100, // msec. polling interval
},
logger: {
level: 'debug',
appenders: {
out: { type: 'stdout' }
},
categories: {
default: { appenders: ['out'], level: 'debug' },
},
},
puppeteer: {
browser: 'chrome',
headless: false,
args: [
"--no-sandbox"
]
},
playwright: {
browserType: 'chromium', // 'chromium' | 'firefox' | 'webkit'
headless: false,
contextOptions: { // passed through to playwright's browser.newContext()
locale: undefined, // e.g. 'ja-JP'. sets Accept-Language and navigator.language
},
},
}
}
static create(commandLineArgs){
this.instance = new Config();
this.instance.merge(Config.DEFAULT_CONFIG)
this.instance.loadConfigFile(this.CONFIG_FILE_PATH);
this.instance.loadConfigFile(this.CONFIG_FILE_PATH + ".local");
let optParser = new OptParser(commandLineArgs);
this.instance.merge(optParser.parse((config, cmdOpt)=>{
switch(cmdOpt.option()){
case "-s":
case "--silent": config.silentMode = true; break;
case "--debug": config.debug = true; break;
default:
let optionKey = cmdOpt.option(true).replace(/--/, '');
if(this.instance.isExists(optionKey)){
Config.assign(this.instance, optionKey, cmdOpt.getValueOrFail())
}else{
const msg = "Unexpected CommandLine Argument, [" + cmdOpt.option() + "]"
console.log(msg);
throw new Error(msg);
}
}
}));
optParser.scriptArguments().forEach((args)=>{
let filePath = args[0] == "/" ? args : path.join(process.cwd(), args);
let stat = fs.statSync(filePath)
let keyName = stat.isDirectory() ? "scenarioDir" : "scenarioFile";
if(!(this.instance[keyName] instanceof Array)){
this.instance[keyName] = []
}
this.instance[keyName].push(args);
})
// apply options
// puppeteer >= 22 renamed the launch option "product" to "browser", and keep backward compatibility.
if(this.instance.puppeteer.product){
this.instance.puppeteer.browser = this.instance.puppeteer.product;
delete this.instance.puppeteer.product;
}
if(this.instance.debug){
// a wait must not time out while you are stopping at a breakpoint
this.instance.mocha.timeout = DEBUG_TIMEOUT_MSEC;
this.instance.autoWaiting.timeout = DEBUG_TIMEOUT_MSEC;
}
if(this.instance.silentMode){
this.instance.puppeteer.headless = true;
this.instance.playwright.headless = true;
this.instance.mocha.reporter = "dot";
this.instance.exitImmediately = true;
}
this.instance.puppeteer.defaultViewport = this.instance.puppeteer.defaultViewport || {};
this.instance.puppeteer.defaultViewport.width = this.instance.width;
this.instance.puppeteer.defaultViewport.height = this.instance.height;
this.instance.playwright.viewport = { width: this.instance.width, height: this.instance.height };
// identifier of the backend and browser-engine combination.
this.instance.browserVariant = this.instance.browser == "playwright"
? `playwright-${this.instance.playwright.browserType}`
: `puppeteer-${this.instance.puppeteer.browser}`;
// validates
if(!["puppeteer", "playwright"].includes(this.instance.browser)){
throw new Error(`config.browser is not allowed! [${this.instance.browser}]`)
}
return this.instance;
}
static get config(){
return this.instance;
}
/**
* @private
*/
loadConfigFile(filePath){
if(fs.existsSync(filePath)){
this.merge(JSON.parse(fs.readFileSync(filePath, 'utf8')));
}
}
clone(){
let cloned = new Config();
cloned.merge(this);
return cloned;
}
merge(source){
Config.merge(this, source);
}
static merge(dest, source){
Object.keys(source).forEach((key)=>{
if(typeof source[key] == "object" && typeof dest[key] == "object"){
this.merge(dest[key], source[key]);
}else{
dest[key] = source[key];
}
});
}
isExists(key){
let parentObj = this;
return !!key.split(".").every((k)=>{
let isExists = parentObj && (k in parentObj);
parentObj = isExists && parentObj[k];
return isExists;
})
}
static isExists(object, key){
if(typeof object != "object") return false;
if(key in object){
return typeof object[key] == "object" ? object[key] : true;
}
}
static assign(config, key, value){
let keys = key.split(".");
keys.reduce((object, key, index)=>{
if(index < keys.length - 1){
if(!object[key]){
object[key] = {}
}
return object[key];
}
switch(typeof object[key]){
case 'number': object[key] = new Number(value); break;
case 'boolean': object[key] = value.toString().toLowerCase() == 'true'; break;
default: object[key] = value; break;
}
}, config);
}
}
module.exports = Config;