How to use runServer method in Playwright Internal

Best JavaScript code snippet using playwright-internal

serve.js

Source:serve.js Github

copy

Full Screen

1/**2 * Description: Serve a project3 * Author: Liam4 * CreatedAt: 2017-1216-12165 * UpdateBy:6 * UpdateAt:7 */ 8var webpack = require('webpack'),9 GMILOG = require ('../util/gmi-log'),10 chokidar = require ('chokidar')11// Generate webpack config object 12var CommonsChunkPlugin = require ("webpack/lib/optimize/CommonsChunkPlugin"),13 path = require ('path'),14 fs = require ('fs'),15 fsExtra = require ('fs-extra'),16 uglifyJsPlugin = webpack.optimize.UglifyJsPlugin,17 srcDir = path.resolve (process.cwd (), 'src'),18 distDir = path.resolve (process.cwd (), 'dist')19// Render Html20var glob = require ('glob'),21 minify = require ('html-minifier').minify22// Generate sass file23var sass = require ('node-sass')24if (fs.existsSync (path.resolve (process.cwd (), 'projectConfig.js'))) {25 var projectConfig = require (path.resolve (process.cwd (), 'projectConfig.js'))26}27// Express28var express = require ('express')29var app = express ()30var opener = require ('opener')31// RunServer Object32RunServer = module.exports = {}33RunServer.run = function () {34 RunServer.readyUp ()35 RunServer.startServe ()36}37RunServer.readyUp = function () {38 RunServer.webpackTool ()39 RunServer.renderHtml ()40 RunServer.renderSass ()41 RunServer.copyAssets ()42 // RunServer.copyJsLib ()43 RunServer.copyLib ()44 RunServer.watch ()45 // RunServer.copyScssLib ()46}47RunServer.startServe = function () {48 app.use (projectConfig.root, express.static (distDir))49 // app.get(projectConfig.root, function (req, res) {50 // res.send('Hello World')51 // res.redirect ('/')52 // })53 if (projectConfig) {54 app.listen (projectConfig.port)55 var browserObject = opener ("http://localhost:" + projectConfig.port + projectConfig.root)56 }57 // console.log (browserObject)58}59RunServer.localhost = function (port) {60 app.use ('/', express.static (path.resolve (process.cwd (), '')))61 app.listen (port)62 var browserTemp = opener ("http://localhost:" + port)63}64RunServer.renderSass = function () {65 setTimeout ( () => {66 sass.render ({67 file: 'src/scss/pages/main.scss',68 includePaths: ['src/scss/pages/'],69 outFile: 'dist/css',70 sourceMap: true,71 outputStyle: 'compressed',72 }, (error, result) => {73 if (error) {74 GMILOG.E_LOG (error)75 } else {76 fsExtra.outputFile ('dist/css/style.min.css', result.css, err => {77 if (err) console.log (err)78 })79 }80 })81 }, 500)82}83RunServer.renderHtml = function () {84 // console.log ("run render : " + srcDir + '/**/*.html')85 glob ('src/pages/**/*.html', {}, (err, files) => {86 // console.log (files)87 if (err) {88 console.log (err)89 }90 if (files.length < 1) {91 console.log ("no files")92 // return93 }94 files.forEach (path => {95 fs.readFile (path, 'utf8', (err, content) => {96 if (err) console.log (err)97 renderRecursive (path, content)98 })99 })100 })101}102RunServer.copyAssets = function () {103 fsExtra.copy ('src/assets/', 'dist/assets/', (err) => {104 if (err) console.log (err)105 console.log ("Assets" + " copied!") 106 })107}108RunServer.copyJsLib = function () {109 fsExtra.copy ('src/js/lib', 'dist/js/lib', (err) => {110 if (err) console.log (err)111 console.log ("js lib" + " copied!") 112 })113}114RunServer.copyLib = function () {115 fsExtra.copy ('src/lib', 'dist/lib', (err) => {116 if (err) console.log (err)117 console.log ("lib" + " copied!") 118 })119}120RunServer.copyScssLib = function () {121 fsExtra.copy ('src/scss/lib', 'dist/css/lib', (err) => {122 if (err) console.log (err)123 console.log ("scss lib" + " copied!") 124 })125}126/**127 * add 128 * unlink129 * unlinkDir130 * change131 * 132 */133RunServer.watch = function () {134 chokidar.watch ('src', {135 // ignored: /^src(\\|\/)js(\\|\/)pages.*\.js$/,136 ignoreInitial: true137 }).on ('all', (event, path) => {138 console.log (`event : ${event} ; path : ${path}`)139 if (/^src(\\|\/)js(\\|\/)pages.*\.js$/.test (path)) {140 console.log (path)141 if (event == "add" || event == "unlink") {142 RunServer.webpackTool (event)143 }144 } else if (/^src(\\|\/)pages.*\.html$/.test (path)) {145 console.log(path)146 RunServer.renderHtml ()147 } else if (/^src(\\|\/)scss(\\|\/)pages.*\.scss$/.test (path)) {148 RunServer.renderSass ()149 } else if (/^src(\\|\/)assets*/.test (path)) {150 console.log (path)151 if (event == "add") {152 fsExtra.copy (path, path.replace ('src', 'dist'), (err) => {153 if (err) console.log (err)154 console.log (path + " copied!") 155 })156 }157 } else if (/^src(\\|\/)lib.*\.js$/.test (path)) {158 if (event != "unlink" && event != "unlinkDir") {159 fsExtra.copy (path, path.replace ('src', 'dist'), (err) => {160 if (err) console.log (err)161 console.log (path + " copied!") 162 })163 }164 }165 })166}167RunServer.webpackTool = function (event) {168 if (event == "add" || event == "unlink") {169 if (RunServer.watching) {170 RunServer.watching.close (() => {171 console.log ("restart watch")172 })173 }174 if (RunServer.myDevConfig != null) {175 RunServer.myDevConfig = null176 }177 if (RunServer.devCompiler != null) {178 RunServer.devCompiler = null179 }180 var JsFileName = getJsFile (),181 EntryFileName = getEntryName ()182 //创建一个webpack配置对象183 RunServer.myDevConfig = Object.create ({184 //允许缓存提高性能185 cache: true,186 //生成sourcemap文件187 devtool: projectConfig.sourceMap || "cheap-module-eval-source-map",188 //多文件入口189 entry: JsFileName,190 output: {191 //__diename返回当前文件所在的路劲192 path: path.resolve (distDir, 'js/'),193 //The publicPath specifies the public URL address of the output files when referenced in a browser.194 // the url to the output directory resolved relative to the HTML page,网站运行时访问的路径195 publicPath: path.resolve (distDir, 'js/'),196 //生成文件的命名197 filename: "[name].js",198 //是未被列在entry中,却又需要被打包出来的文件命名配置,在按需加载(异步)模块的时候,这样的文件是没有被列在entry中的,如使用CommonJS的方式异步加载模块199 /*200 require.ensure(["modules/tips.jsx"], function(require) {201 var a = require("modules/tips.jsx");202 // ...203 }, 'tips');204 异步加载的模块是要以文件形式加载哦,所以这时生成的文件名是以chunkname配置的,生成出的文件名就是tips.min.js。205 */206 chunkFilename: "[chunkhash].js"207 },208 resolve: {209 //查找module的话从这里开始查找210 //root: '/pomy/github/flux-example/src', //绝对路径211 //自动扩展文件后缀名,意味着我们require模块可以省略不写后缀名212 //extensions: ['', '.js', '.json', '.scss'],213 //模块别名定义,方便后续直接引用别名,无须多写长长的地址214 alias: {215 // zepto: srcDir + "/js/lib/zepto.min.js",216 core: srcDir + "/js/core",217 util: srcDir + "/js/util",218 tool: srcDir + "/js/tool",219 }220 },221 module: {222 //加载器配置223 //解析出zepto的路径,然后使用加载器进行zepto的改变224 rules: [{225 test: /\.js$/,226 exclude: [/node_modules/],227 use: [{228 loader: 'babel-loader',229 options: {230 presets: ['es2015']231 }232 }],233 },234 // Loaders for other file types can go here235 ],236 },237 plugins: [238 new CommonsChunkPlugin ({name: 'common', chunks: EntryFileName}),239 new uglifyJsPlugin ({240 // 最紧凑的输出241 beautify: projectConfig.jsBeautify || true,242 // 删除所有的注释243 comments: projectConfig.jsComments || false,244 compress: {245 // 在UglifyJs删除没有用到的代码时不输出警告246 warnings: projectConfig.jsWarnings || false,247 // 删除所有的 `console` 语句248 // 还可以兼容ie浏览器249 drop_console: projectConfig.jsDrop_console || false,250 // 内嵌定义了但是只用到一次的变量251 collapse_vars: projectConfig.jsCollapse_vars || false,252 // 提取出出现多次但是没有定义成变量去引用的静态值253 reduce_vars: projectConfig.jsReduce_vars || false,254 }255 })256 ]257 //当我们想在项目中require一些其他的类库或者API,而又不想让这些类库的源码被构建到运行时文件中,这在实际开发中很有必要。此时我们就可以通过配置externals参数来解决这个问题258 // externals: {259 // "jquery": "jQuery"260 // }261 })262 RunServer.devCompiler = webpack (RunServer.myDevConfig)263 RunServer.watching = RunServer.devCompiler.watch ({ // watch options:264 aggregateTimeout: 300, // wait so long for more changes265 poll: false // use polling instead of native watchers266 // pass a number to set the polling interval267 }, function (err, stats) {268 if (err) GMILOG.E_LOG (err)269 // GMILOG.N_LOG ("-")270 if (!RunServer.statsHash) {271 RunServer.statsHash = stats.hash272 GMILOG.N_LOG (stats.toString ({273 profile: true, colors: true274 }))275 } else {276 if (RunServer.statsHash != stats.hash) {277 GMILOG.N_LOG (stats.toString ({278 profile: true, colors: true279 })) 280 }281 }282 }) 283 } else {284 var JsFileName = getJsFile (),285 EntryFileName = getEntryName ()286 //创建一个webpack配置对象287 RunServer.myDevConfig = Object.create ({288 //允许缓存提高性能289 cache: true,290 //生成sourcemap文件291 devtool: projectConfig.sourceMap || "cheap-module-eval-source-map",292 //多文件入口293 entry: JsFileName,294 output: {295 //__diename返回当前文件所在的路劲296 path: path.resolve (distDir, 'js/'),297 //The publicPath specifies the public URL address of the output files when referenced in a browser.298 // the url to the output directory resolved relative to the HTML page,网站运行时访问的路径299 publicPath: path.resolve (distDir, 'js/'),300 //生成文件的命名301 filename: "[name].js",302 //是未被列在entry中,却又需要被打包出来的文件命名配置,在按需加载(异步)模块的时候,这样的文件是没有被列在entry中的,如使用CommonJS的方式异步加载模块303 /*304 require.ensure(["modules/tips.jsx"], function(require) {305 var a = require("modules/tips.jsx");306 // ...307 }, 'tips');308 异步加载的模块是要以文件形式加载哦,所以这时生成的文件名是以chunkname配置的,生成出的文件名就是tips.min.js。309 */310 chunkFilename: "[chunkhash].js"311 },312 resolve: {313 //查找module的话从这里开始查找314 //root: '/pomy/github/flux-example/src', //绝对路径315 //自动扩展文件后缀名,意味着我们require模块可以省略不写后缀名316 //extensions: ['', '.js', '.json', '.scss'],317 //模块别名定义,方便后续直接引用别名,无须多写长长的地址318 alias: {319 // zepto: srcDir + "/js/lib/zepto.min.js",320 core: srcDir + "/js/core",321 util: srcDir + "/js/util",322 tool: srcDir + "/js/tool"323 }324 },325 module: {326 //加载器配置327 //解析出zepto的路径,然后使用加载器进行zepto的改变328 rules: [{329 test: /\.js$/,330 exclude: [/node_modules/],331 use: [{332 loader: 'babel-loader',333 options: {334 presets: ['es2015']335 }336 }],337 },338 // Loaders for other file types can go here339 ],340 },341 plugins: [342 new CommonsChunkPlugin ({name: 'common', chunks: EntryFileName}),343 new uglifyJsPlugin ({344 // 最紧凑的输出345 beautify: projectConfig.jsBeautify || true,346 // 删除所有的注释347 comments: projectConfig.jsComments || false,348 compress: {349 // 在UglifyJs删除没有用到的代码时不输出警告350 warnings: projectConfig.jsWarnings || false,351 // 删除所有的 `console` 语句352 // 还可以兼容ie浏览器353 drop_console: projectConfig.jsDrop_console || false,354 // 内嵌定义了但是只用到一次的变量355 collapse_vars: projectConfig.jsCollapse_vars || false,356 // 提取出出现多次但是没有定义成变量去引用的静态值357 reduce_vars: projectConfig.jsReduce_vars || false,358 }359 })360 ]361 //当我们想在项目中require一些其他的类库或者API,而又不想让这些类库的源码被构建到运行时文件中,这在实际开发中很有必要。此时我们就可以通过配置externals参数来解决这个问题362 // externals: {363 // "jquery": "jQuery"364 // }365 })366 RunServer.devCompiler = webpack (RunServer.myDevConfig)367 RunServer.watching = RunServer.devCompiler.watch ({ // watch options:368 aggregateTimeout: 300, // wait so long for more changes369 poll: false // use polling instead of native watchers370 // pass a number to set the polling interval371 }, function (err, stats) {372 if (err) GMILOG.E_LOG (err)373 // GMILOG.N_LOG ("-")374 if (!RunServer.statsHash) {375 RunServer.statsHash = stats.hash376 GMILOG.N_LOG (stats.toString ({377 profile: true, colors: true378 }))379 } else {380 if (RunServer.statsHash != stats.hash) {381 GMILOG.N_LOG (stats.toString ({382 profile: true, colors: true383 })) 384 }385 }386 }) 387 }388 // RunServer.devCompiler.run ((err, stats) => {389 // if (err) GMILOG.E_LOG (err)390 // // GMILOG.N_LOG ("-")391 // if (!RunServer.statsHash) {392 // RunServer.statsHash = stats.hash393 // GMILOG.N_LOG (stats.toString ({394 // profile: true, colors: true395 // }))396 // } else {397 // if (RunServer.statsHash != stats.hash) {398 // GMILOG.N_LOG (stats.toString ({399 // profile: true, colors: true400 // })) 401 // }402 // }403 // }) 404}405function renderRecursive (path, content) {406 // console.log (content + "\n-------" + path)407 let regexOuter = /<\%\ \@\@include="(.*?)"\ \%>/408 let regexInclude = /include="(.*?)"/409 let regexInner = />(.*?)</410 let rootReg = /\@PATH\@/411 let versionReg = /\@VERSION\@/412 // let COMMENT_PSEUDO_COMMENT_OR_LT_BANG = new RegExp(413 // '<!--[\\s\\S]*?(?:-->)?'414 // + '<!---+>?' // A comment with no body415 // + '|<!(?![dD][oO][cC][tT][yY][pP][eE]|\\[CDATA\\[)[^>]*>?'416 // + '|<[?][^>]*>?', // A pseudo-comment417 // 'g');418 let cleanComment = /\<\!\-\-(\ |)(.*?)\-\-\>/419 while (cleanComment.test (content)) {420 content = content.replace (cleanComment, '')421 }422 // while (COMMENT_PSEUDO_COMMENT_OR_LT_BANG.test (content)) {423 // content = content.replace (COMMENT_PSEUDO_COMMENT_OR_LT_BANG, '')424 // }425 content = content.replace (regexOuter, match => {426 let matchInclude = match427 let contentUpdated = ''428 // console.log (content)429 // console.log (matchInclude)430 match.replace (regexInclude, match => {431 // console.log (match)432 match.replace (/"(.*?)"/, matchIncludeFile => {433 let includeFileName = matchIncludeFile.substring (1, matchIncludeFile.length - 1)434 // console.log (path)435 let pathRelative = path.split ('/').slice (0, -1).join ('/')436 // console.log (pathRelative)437 if (/^\//.test (includeFileName)) {438 includeFileName = includeFileName.replace (/^\//, '')439 pathRelative = "src/pages"440 }441 if (/^includes\//.test (includeFileName)) {442 includeFileName = includeFileName.replace (/^includes\//, '')443 pathRelative = "src/pages/includes"444 }445 while (true) {446 if (/^\.\//.test (includeFileName)) {447 includeFileName = includeFileName.replace (/^\.\//, '')448 } else {449 break450 }451 }452 while (true) {453 if (/^\.\.\//.test (includeFileName)) {454 includeFileName = includeFileName.replace (/^\.\.\//, '')455 pathRelative = pathRelative.split ('/').slice (0, -1).join ('/')456 } else {457 break458 }459 }460 // console.log (includeFileName)461 // includeFileName.replace (/^\.\//, currentPath => {462 // console.log (currentPath)463 // })464 // console.log (includeFileName)465 let includeFilePath = pathRelative + "/" + includeFileName466 // contentUpdated = ' ' + matchInclude.replace (regexOuter, '').trim ()467 contentUpdated = matchInclude.replace (regexOuter, match => {468 let content = ''469 // console.log (includeFilePath)470 if (!fs.existsSync (includeFilePath)) {471 GMILOG.E_LOG (includeFilePath + " File not found!")472 } else {473 content = fs.readFileSync (includeFilePath, 'utf8')474 return '' + content + ''475 }476 })477 })478 })479 return contentUpdated480 })481 // console.log (content + "\n-------" + path)482 // console.log (/<\%\ \@\@include="(.*?)"\ \%>/.test (content))483 if (/<\%\ \@\@include="(.*?)"\ \%>/.test (content)) {484 renderRecursive (path, content)485 } else {486 let filename = path.replace (/^src/, 'dist').replace (/pages\//, '')487 while (versionReg.test (content)) {488 content = content.replace (versionReg, projectConfig.version)489 }490 while (rootReg.test (content)) {491 content = content.replace (rootReg, projectConfig.root)492 }493 // console.log (filename)494 fsExtra.outputFile (filename, minify (content, {collapseWhitespace: true, removeComments: true}), err => {495 if (err) console.log (err)496 })497 }498}499//获取所有js\pages目录下的文件夹名称500function getDirName () {501 var fileList = []502 var jsPath = path.resolve (srcDir, 'js/pages')503 // GMILOG.N_LOG (jsPath);504 if (!fs.existsSync (jsPath)) {505 GMILOG.E_LOG (jsPath + " is not exist!")506 } else {507 var dirs = fs.readdirSync (jsPath)508 dirs.forEach (function (item) {509 fileList.push (item)510 })511 }512 // GMILOG.N_LOG (fileList);513 return fileList514}515//遍历获取js文件的数组516function getJsFile () {517 //获取js目录下所有文件夹名字数组518 var fileList = getDirName ()519 var totalFiles = {}520 var matchs = [],521 files = {}522 if (fileList.length > 0) {523 fileList.forEach (function (fileItem) {524 if (fileItem.match (/(.+)\.js$/)) {525 matchs = fileItem.match (/(.+)\.js$/)526 if (matchs) {527 files[matchs[1]] = path.resolve (srcDir, 'js/pages', fileItem)528 }529 } else {530 var jsPath = path.resolve (srcDir, 'js/pages/' + fileItem)531 // if (!fs.existsSync (jsPath)) {532 // GMILOG.E_LOG (jsPath + " is not exist!")533 // } else {534 var dirs = fs.readdirSync (jsPath)535 dirs.forEach (function (item) {536 matchs = item.match (/(.+)\.js$/)537 if (matchs) {538 files[matchs[1]] = path.resolve (srcDir, 'js/pages/' + fileItem, item)539 }540 });541 // }542 }543 })544 }545 return files546 //synchronous read dir,return an array of filenames excluding '.' and '..'547 // console.log("this is detected js: " + dirs);548 //declare matchs array and file object will be used later549 //use reg match any.js file550}551//遍历获取js文件的数组552function getEntryName () {553 //获取js目录下所有文件夹名字数组554 var fileList = getDirName ()555 var totalFiles = {}556 var entryName = []557 var matchs = [],558 files = {}559 if (fileList.length > 0) {560 fileList.forEach (function (fileItem) {561 if (fileItem.match (/(.+)\.js$/)) {562 matchs = fileItem.match (/(.+)\.js$/)563 if (matchs) {564 entryName.push (matchs[1]);565 }566 } else {567 var jsPath = path.resolve (srcDir, 'js/pages/' + fileItem)568 // if (!fs.existsSync (jsPath)) {569 // GMILOG.E_LOG (jsPath + " is not exist!")570 // } else {571 var dirs = fs.readdirSync (jsPath)572 dirs.forEach (function (item) {573 matchs = item.match (/(.+)\.js$/)574 if (matchs) {575 entryName.push (matchs[1])576 }577 })578 // }579 }580 })581 }582 return entryName;583 //synchronous read dir,return an array of filenames excluding '.' and '..'584 // console.log("this is detected js: " + dirs);585 //declare matchs array and file object will be used later586 //use reg match any.js file...

Full Screen

Full Screen

app-server-test.js

Source:app-server-test.js Github

copy

Full Screen

...25 });26 }).to.throw(/FastBootAppServer must be provided with either a distPath or a downloader option, but not both/);27 });28 it("serves an HTTP 500 response if the app can't be found", function() {29 return runServer('not-found-server')30 .then(() => request('http://localhost:3000'))31 .then(response => {32 expect(response.statusCode).to.equal(500);33 expect(response.body).to.match(/No Application Found/);34 });35 });36 it("serves static assets", function() {37 return runServer('basic-app-server')38 .then(() => request('http://localhost:3000/assets/fastboot-test.js'))39 .then(response => {40 expect(response.statusCode).to.equal(200);41 expect(response.body).to.contain('"use strict";');42 })43 .then(() => request('http://localhost:3000/'))44 .then(response => {45 expect(response.statusCode).to.equal(200);46 expect(response.body).to.contain('Welcome to Ember');47 });48 });49 it("returns a 404 status code for non-existent assets", function() {50 return runServer('basic-app-server')51 .then(() => request('http://localhost:3000/assets/404-does-not-exist.js'))52 .then(response => {53 expect(response.statusCode).to.equal(404);54 expect(response.body).to.match(/Not Found/);55 })56 .then(() => request('http://localhost:3000/'))57 .then(response => {58 expect(response.statusCode).to.equal(200);59 expect(response.body).to.contain('Welcome to Ember');60 });61 });62 it("executes beforeMiddleware", function() {63 return runServer('before-middleware-server')64 .then(() => request('http://localhost:3000'))65 .then(response => {66 expect(response.statusCode).to.equal(418);67 expect(response.headers['x-test-header']).to.equal('testing');68 expect(response.body).to.equal(JSON.stringify({ send: 'json back'}));69 });70 });71 it("executes afterMiddleware when there is an error", function() {72 return runServer('after-middleware-server')73 .then(() => request('http://localhost:3000'))74 .then(response => {75 expect(response.body).to.not.match(/error/);76 expect(response.headers['x-test-header']).to.equal('testing');77 });78 });79 it("returns a 401 status code for non-authenticated request", function() {80 return runServer('auth-app-server')81 .then(() => request('http://localhost:3000/'))82 .then(response => {83 expect(response.statusCode).to.equal(401);84 expect(response.headers['www-authenticate']).equal('Basic realm=Authorization Required');85 })86 .then(() => request({ uri: 'http://localhost:3000/', headers: { 'Authorization': 'Basic dG9tc3Rlcjp6b2V5' }}))87 .then(response => {88 expect(response.statusCode).to.equal(200);89 expect(response.body).to.contain('Welcome to Ember');90 });91 });92 it("responds on the configured host and port", function() {93 return runServer('ipv4-app-server')94 .then(() => request('http://127.0.0.1:4100/'))95 .then((response) => {96 expect(response.statusCode).to.equal(200);97 expect(response.body).to.contain('Welcome to Ember');98 });99 });100 it("allows setting sandbox globals", function() {101 return runServer('sandbox-globals-app-server')102 .then(() => request('http://localhost:3000/'))103 .then((response) => {104 expect(response.statusCode).to.equal(200);105 expect(response.body).to.contain('Welcome to Ember from MY GLOBAL!');106 });107 });108 it("allows changing of distpath", function() {109 return runServer('dist-path-change-server')110 .then(() => request('http://localhost:3000/'))111 .then((response) => {112 expect(response.statusCode).to.equal(200);113 expect(response.body).to.contain('Welcome to Ember from MY GLOBAL!');114 });115 });116});117function runServer(name) {118 return new Promise((res, rej) => {119 let serverPath = path.join(__dirname, 'fixtures', `${name}.js`);120 server = fork(serverPath, {121 silent: true122 });123 server.on('error', rej);124 server.stdout.on('data', data => {125 if (data.toString().match(/HTTP server started/)) {126 res();127 }128 });129 server.stderr.on('data', data => {130 console.log(data.toString());131 });...

Full Screen

Full Screen

server.js

Source:server.js Github

copy

Full Screen

...21let server;22// this function starts our server and returns a Promise.23// In our test code, we need a way of asynchronously starting24// our server, since we'll be dealing with promises there.25function runServer() {26 const port = process.env.PORT || 8080;27 return new Promise((resolve, reject) => {28 server = app.listen(port, () => {29 console.log(`Your app is listening on port ${port}`);30 resolve(server);31 }).on('error', err => {32 reject(err)33 });34 });35}36// like `runServer`, this function also needs to return a promise.37// `server.close` does not return a promise on its own, so we manually38// create one.39function closeServer() {40 return new Promise((resolve, reject) => {41 console.log('Closing server');42 server.close(err => {43 if (err) {44 reject(err);45 // so we don't also call `resolve()`46 return;47 }48 resolve();49 });50 });51}52// if server.js is called directly (aka, with `node server.js`), this block53// runs. but we also export the runServer command so other code (for instance, test code) can start the server as needed.54if (require.main === module) {55 runServer().catch(err => console.error(err));56};...

Full Screen

Full Screen

process.js

Source:process.js Github

copy

Full Screen

1export function getAppProcesses() {2 return [3 {'name': 'web', 'cmd': 'python manage.py runserver 0.0.0.0:80', 'status': 1, 'id': '1'},4 {'name': 'web', 'cmd': 'python manage.py runserver 0.0.0.0:80', 'status': 1, 'id': '2'},5 {'name': 'web', 'cmd': 'python manage.py runserver 0.0.0.0:80', 'status': 1, 'id': '3'},6 {'name': 'web', 'cmd': 'python manage.py runserver 0.0.0.0:80', 'status': 1, 'id': '4'},7 {'name': 'web', 'cmd': 'python manage.py runserver 0.0.0.0:80', 'status': 1, 'id': '5'},8 {'name': 'web', 'cmd': 'python manage.py runserver 0.0.0.0:80', 'status': 1, 'id': '6'},9 {'name': 'web', 'cmd': 'python manage.py runserver 0.0.0.0:80', 'status': 1, 'id': '7'},10 {'name': 'web', 'cmd': 'python manage.py runserver 0.0.0.0:80', 'status': 1, 'id': '8'},11 {'name': 'web', 'cmd': 'python manage.py runserver 0.0.0.0:80', 'status': 1, 'id': '9'},12 {'name': 'web', 'cmd': 'python manage.py runserver 0.0.0.0:80', 'status': 1, 'id': '10'},13 {'name': 'web', 'cmd': 'python manage.py runserver 0.0.0.0:80', 'status': 1, 'id': '11'},14 {'name': 'web', 'cmd': 'python manage.py runserver 0.0.0.0:80', 'status': 1, 'id': '12'},15 {'name': 'web', 'cmd': 'python manage.py runserver 0.0.0.0:80', 'status': 1, 'id': '13'},16 {'name': 'web', 'cmd': 'python manage.py runserver 0.0.0.0:80', 'status': 1, 'id': '14'},17 {'name': 'web', 'cmd': 'python manage.py runserver 0.0.0.0:80', 'status': 1, 'id': '15'},18 {'name': 'web', 'cmd': 'python manage.py runserver 0.0.0.0:8000', 'status': 0, 'id': '16'}19 ]20}21export function getAppProcessTypes() {22 return [23 {'name': 'web'}, {'name': 'celery'}, {'name': 'cbeat'}, {'name': 'cron'}, {'name': 'sync1'}, {'name': 'sync2'}24 ]...

Full Screen

Full Screen

gulpfile.js

Source:gulpfile.js Github

copy

Full Screen

1'use strict';2var gulp = require('gulp');3var rename = require('gulp-rename');4var sass = require('gulp-sass');5var cleanCSS = require('gulp-clean-css');6var uglify = require('gulp-uglify');7var os = require('os');8var spawn = require('child_process').spawn;9gulp.task('build-css', function() {10 return gulp.src('static/scss/style.scss')11 .pipe(sass())12 .pipe(cleanCSS({compatibility: 'ie8'}))13 .pipe(rename({ extname: '.min.css' }))14 .pipe(gulp.dest('static/css/'));15});16gulp.task('build-js', function() {17 return gulp.src('static/js/script.js')18 .pipe(uglify())19 .pipe(rename({ extname: '.min.js' }))20 .pipe(gulp.dest('static/js/'));21});22gulp.task('runserver', ['build-css', 'build-js'], function() {23 gulp.watch('static/scss/style.scss', ['build-css']);24 gulp.watch('static/js/script.js', ['build-js']);25 // Compatibility across all platforms26 const pythonPath = (os.platform() === 'win32' ? '/scripts/' : '/bin/') + 'python';27 var runserver = spawn(28 process.env['VIRTUAL_ENV'] + pythonPath, ['manage.py', 'runserver'], { stdio: 'inherit' }29 );30 runserver.on('close', function(code) {31 if(code !== 0) {32 console.error('Django runserver exited with error code: ' + code);33 } else {34 console.log('Django runserver exited normally.');35 }36 });...

Full Screen

Full Screen

test-sever.js

Source:test-sever.js Github

copy

Full Screen

1const mockstarLocalServer = require('../../lib');2let runServer;3function start(opts = {}) {4 return new Promise((resolve, reject) => {5 mockstarLocalServer6 .findAvailablePort(9528)7 .then(port => {8 runServer = mockstarLocalServer.startServer(9 Object.assign({}, opts, {port: port}),10 (isSuccess, data) => {11 isSuccess ? resolve(data) : reject(data);12 },13 );14 })15 .catch(err => {16 reject(err);17 });18 });19}20function stop() {21 if (!runServer || typeof runServer.stop !== 'function') {22 return;23 }24 // let t1 = Date.now();25 runServer.stop(() => {26 // console.log('-close success-', Date.now() - t1);27 });28}29module.exports = {30 start: start,31 stop: stop,...

Full Screen

Full Screen

coalescing.js

Source:coalescing.js Github

copy

Full Screen

1'use strict';2const runServer = function (port) {3 console.log(`Server running on port ${port}.`);4};5runServer(3000);6runServer();7const runServer = function (port = 3000) {8 console.log(`Server running on port ${port}.`);9};10const runServer = function (port = 3000) {11 port = port || 3000; //falsy12 console.log(`Server running on port ${port}.`);13};14runServer(4000);15runServer(undefined);16runServer(0); //falsy17const runServer = function (port = 3000) {18 port = port ?? 3000; //null or undefined19 console.log(`Server running on port ${port}.`);20};21runServer(4000);22runServer(undefined);...

Full Screen

Full Screen

shorthand.js

Source:shorthand.js Github

copy

Full Screen

2const runServer = function (port = 3000) {3 port = port ?? 3000; //null or undefined4 console.log(`Server running on port ${port}.`);5};6runServer(4000);7runServer(undefined);8runServer(0); //falsy9let i = 5;10i = i + 1;11i += 1;12i++;13i = i + 2;14i += 2;15port = port + 3000;16port += 3000;17const runServer = function (port = 3000) {18 port ??= 3000; //null or undefined19 console.log(`Server running on port ${port}.`);20};21runServer(4000);22runServer(undefined);...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const playwright = require('playwright');2const { runServer } = require('playwright/lib/server/playwrightServer');3(async () => {4 const server = await runServer();5 const browser = await playwright.chromium.connectOverCDP({6 endpointURL: server.wsEndpoint(),7 });8 const context = await browser.newContext();9 const page = await context.newPage();10 await page.screenshot({ path: 'example.png' });11 await browser.close();12 await server.close();13})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const server = require('playwright/test/lib/server/server');2const { runServer } = server;3const { chromium } = require('playwright');4(async () => {5 const browser = await chromium.launch();6 const context = await browser.newContext();7 const page = await context.newPage();8 await page.screenshot({ path: 'google.png' });9 await browser.close();10})();11runServer();12module.exports = {13 use: {14 },15};

Full Screen

Using AI Code Generation

copy

Full Screen

1const { runServer } = require('@playwright/test/lib/server/server');2const server = await runServer({ port: 8080 });3console.log(server.PREFIX);4const { runBrowserServer } = require('@playwright/test/lib/server/browserServer');5const browserServer = await runBrowserServer('chromium');6console.log(browserServer.PREFIX);7const { runLauncher } = require('@playwright/test/lib/server/launcher');8const launcher = await runLauncher();9console.log(launcher.PREFIX);10const { runBrowserType } = require('@playwright/test/lib/server/browserType');11const browserType = await runBrowserType('chromium');12console.log(browserType.PREFIX);13const { runBrowserContext } = require('@playwright/test/lib/server/browserContext');14const browserContext = await runBrowserContext();15console.log(browserContext.PREFIX);16const { runBrowser } = require('@playwright/test/lib/server/browser');17const browser = await runBrowser('chromium');18console.log(browser.PREFIX);19const { runPage } = require('@playwright/test/lib/server/page');20const page = await runPage();21console.log(page.PREFIX);22const { runFrame } = require('@playwright/test/lib/server/frame');23const frame = await runFrame();24console.log(frame.PREFIX);25const { runElementHandle } = require('@playwright/test/lib/server/elementHandler');26const elementHandle = await runElementHandle();27console.log(elementHandle.PREFIX);28const { runJSHandle } = require('@playwright/test/lib/server/jsHandle');29const jsHandle = await runJSHandle();30console.log(jsHandle.PREFIX);31const { runConsoleMessage } = require('@playwright/test/lib/server/consoleMessage');32const consoleMessage = await runConsoleMessage();33console.log(consoleMessage.PREFIX);

Full Screen

Using AI Code Generation

copy

Full Screen

1(async () => {2 const server = await runServer({3 args: [path.resolve(__dirname, 'server.js')],4 });5 await server.stop();6})();7const http = require('http');8const server = http.createServer((req, res) => {9 res.end('Hello World!');10});11server.listen(3000);

Full Screen

Using AI Code Generation

copy

Full Screen

1const { runServer } = require('playwright-core/lib/server/playwright');2runServer(3000);3const http = require('http');4const server = http.createServer((req, res) => {5 res.writeHead(200, { 'Content-Type': 'text/plain' });6 res.end('Hello World7');8});9server.listen(3000, '

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Internal automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful