Best JavaScript code snippet using stryker-parent
app.js
Source:app.js
1require('dotenv').config();2const express=require("express");3const mongoose = require("mongoose");4const bcrypt = require("bcrypt");5const multer = require('multer');6const {GridFsStorage} = require('multer-gridfs-storage');7const path = require("path");8const app=express();9app.set("view engine","ejs");10app.use(express.urlencoded({extended:true}));11app.use(express.static("public"));12mongoose.connect("mongodb+srv://"+process.env.DB_USER+":"+process.env.DB_PASS+"@cluster0.hzq90.mongodb.net/studyDB", {useNewUrlParser: true});13let gfs;14mongoose.connection.once('open',()=>{15 gfs= new mongoose.mongo.GridFSBucket(mongoose.connection.db,{16 bucketName:'fs'17 });18});19const storage = new GridFsStorage({20 url: "mongodb+srv://"+process.env.DB_USER+":"+process.env.DB_PASS+"@cluster0.hzq90.mongodb.net/studyDB",21 file: (req, file) => {22 return {23 filename: Date.now()+"-"+file.originalname24 };25 }26});27const upload = multer({storage}); 28const postSchema = new mongoose.Schema ({29 author:String,30 title:String,31 description:String,32 posttime:String,33 files:[String]34});35const Post =new mongoose.model("Post",postSchema);36const testSchema = new mongoose.Schema ({37 title:String,38 description:String,39 duetime:String,40 maxmarks:Number,41 status:String,42 marks:[{43 name:String,44 id:String,45 mark:Number,46 files:[],47 isSub:Boolean48 }],49 files:[String]50});51const Test =new mongoose.model("Test",testSchema);52const assignmentSchema = new mongoose.Schema ({53 title:String,54 description:String,55 duetime:String,56 maxmarks:Number,57 status:String,58 marks:[{59 name:String,60 id:String,61 mark:Number,62 files:[],63 isSub:Boolean64 }],65 files:[String]66});67const Assignment =new mongoose.model("Assignment",assignmentSchema);68const classSchema = new mongoose.Schema ({69 name:String,70 code:String,71 teacher: String,72 students:[{ type: mongoose.Schema.Types.ObjectId, ref: 'Student' }],73 posts:[{ type: mongoose.Schema.Types.ObjectId, ref: 'Post' }],74 tests:[{ type: mongoose.Schema.Types.ObjectId, ref: 'Test' }],75 assignments:[{ type: mongoose.Schema.Types.ObjectId, ref: 'Assignment' }]76});77const Class = new mongoose.model("Class", classSchema);78const studentSchema = new mongoose.Schema ({79 name:String,80 email: String,81 password: String,82 phone:Number,83 classes:[{ type: mongoose.Schema.Types.ObjectId, ref: 'Class' }],84 periods:[[String]]85});86 87const Student = new mongoose.model("Student", studentSchema);88const teacherSchema = new mongoose.Schema ({89 name:String,90 email: String,91 password: String,92 phone:Number,93 classes:[{ type: mongoose.Schema.Types.ObjectId, ref: 'Class' }],94 periods:[[String]]95});96 97const Teacher = new mongoose.model("Teacher", teacherSchema);98 99function checkdue(){100 Test.find({},(e,foundtests)=>{101 if(e){102 console.log(e);103 }else{104 foundtests.forEach(test=>{105 if(new Date(test.duetime)<new Date()){106 test.status="ended";107 test.save();108 }109 });110 } 111 });112 Assignment.find({},(e,foundassignment)=>{113 if(e){114 console.log(e);115 }else{116 foundassignment.forEach(a=>{117 if(new Date(a.duetime)<new Date()){118 a.status="ended";119 a.save();120 }121 });122 } 123 });124}125 // homepage126app.get("/",(req,res)=>{127 res.render("home",{128 regerror:"",129 logerror:""130 });131});132app.get('/:filename', (req, res) => {133 const file = gfs134 .find({135 filename: req.params.filename,136 })137 .toArray((err, files) => {138 if (!files || files.length === 0) {139 return res.status(404).json({140 err: 'no files exist',141 });142 }143 gfs.openDownloadStreamByName(req.params.filename).pipe(res);144 });145});146 //enrollment147app.post("/stureg", function(req, res){148 const email=req.body.email.toLowerCase();149 Student.findOne({email:email},(e,foundUser)=>{150 if(e){151 console.log(e);152 }else{153 if(foundUser){154 res.render("home",{155 regerror:"User already registered!!",156 logerror:""157 });158 }else{159 bcrypt.hash(req.body.password, 10, function(e, hash) {160 if(e){161 console.log(e);162 }else{ 163 const newStudent = new Student({164 email: req.body.email.toLowerCase(),165 name:req.body.name,166 phone:req.body.phone,167 password: hash,168 periods:[169 ["Monday","N/A","N/A","N/A","N/A","N/A"],170 ["Tuesday","N/A","N/A","N/A","N/A","N/A"],171 ["wednesday","N/A","N/A","N/A","N/A","N/A"],172 ["Thursday","N/A","N/A","N/A","N/A","N/A"],173 ["Friday","N/A","N/A","N/A","N/A","N/A"]174 ]175 });176 177 newStudent.save(function(err){178 if (err) {179 console.log(err);180 } else {181 res.render("student",{182 name:req.body.name,183 email: req.body.email.toLowerCase(),184 classes:[],185 error:""186 });187 }188 });189 }190 });191 }192 }193 });194});195app.post("/teareg", function(req, res){196 const email=req.body.email.toLowerCase();197 Teacher.findOne({email:email},(e,foundUser)=>{198 if(e){199 console.log(e);200 }else{201 if(foundUser){202 res.render("home",{203 regerror:"User already registered!!",204 logerror:""205 });206 }else{207 bcrypt.hash(req.body.password, 10, function(e, hash) {208 if(e){209 console.log(e);210 }else{ 211 const newTeacher = new Teacher({212 email: req.body.email.toLowerCase(),213 name:req.body.name,214 phone:req.body.phone,215 password: hash,216 periods:[217 ["Monday","N/A","N/A","N/A","N/A","N/A"],218 ["Tuesday","N/A","N/A","N/A","N/A","N/A"],219 ["wednesday","N/A","N/A","N/A","N/A","N/A"],220 ["Thursday","N/A","N/A","N/A","N/A","N/A"],221 ["Friday","N/A","N/A","N/A","N/A","N/A"]222 ]223 });224 225 newTeacher.save(function(err){226 if (err) {227 console.log(err);228 } else {229 res.render("teacher",{230 name:req.body.name,231 email: req.body.email.toLowerCase(),232 classes:[],233 error:""234 });235 }236 });237 }238 });239 }240 }241 });242});243app.post("/stulog", function(req, res){244 const email=req.body.email.toLowerCase();245 const password=req.body.password;246 247 Student.findOne({email:email}).populate('classes').exec((e,foundUser)=>{248 if (e) {249 console.log(e);250 } else {251 if (foundUser) {252 bcrypt.compare(password, foundUser.password, function(err, result) {253 if (result === true) {254 res.render("student",{255 name:foundUser.name,256 email:foundUser.email,257 classes:foundUser.classes,258 error:""259 });260 }else{261 res.render("home",{262 regerror:"",263 logerror:"Invalid username or password!!"264 });265 }266 });267 }else{268 res.render("home",{269 regerror:"",270 logerror:"Invalid username or password!!"271 });272 }273 }274 });275});276app.post("/tealog", function(req, res){277 const email=req.body.email.toLowerCase();278 const password = req.body.password;279 Teacher.findOne({email:req.body.email}).populate('classes').exec((e,foundUser)=>{280 if (e) {281 console.log(e);282 } else {283 if (foundUser) {284 bcrypt.compare(password, foundUser.password, function(err, result) {285 if (result === true) {286 res.render("teacher",{287 name:foundUser.name,288 email:foundUser.email,289 classes:foundUser.classes,290 error:""291 });292 }else{293 res.render("home",{294 regerror:"",295 logerror:"Invalid username or password!!"296 });297 }298 });299 }else{300 res.render("home",{301 regerror:"",302 logerror:"Invalid username or password!!"303 });304 }305 }306 });307});308 // class and userhomepages309app.post("/home",(req,res)=>{310 Teacher.findOne({email:req.body.email}).populate('classes').exec((e,foundUser)=>{311 if(e){312 console.log(e);313 }else{314 res.render("teacher",{315 name:foundUser.name,316 email:foundUser.email,317 classes:foundUser.classes,318 error:""319 });320 }321 });322});323app.post("/shome",(req,res)=>{324 Student.findOne({email:req.body.email}).populate('classes').exec((e,foundUser)=>{325 if(e){326 console.log(e);327 }else{328 res.render("student",{329 name:foundUser.name,330 email:foundUser.email,331 classes:foundUser.classes,332 error:""333 });334 }335 });336});337app.post("/class",(req,res)=>{338 Class.findOne({code:req.body.code})339 .populate('posts').populate('tests').populate('assignments').populate('students').340 exec((e,foundClass)=>{341 if(e){342 console.log(e);343 }else{344 checkdue();345 res.render("class",{346 code:foundClass.code,347 name:foundClass.teacher,348 email:req.body.email,349 classname:foundClass.name,350 students:foundClass.students,351 posts:foundClass.posts,352 tests:foundClass.tests,353 assign:foundClass.assignments354 });355 }356 });357});358app.post("/sclass",(req,res)=>{359 Class.findOne({code:req.body.code})360 .populate('posts').populate('tests').populate('assignments').populate('students').361 exec((e,foundClass)=>{362 if(e){363 console.log(e);364 }else{365 res.render("sclass",{366 name:foundClass.teacher,367 email:req.body.email,368 classname:foundClass.name,369 students:foundClass.students,370 code:foundClass.code,371 posts:foundClass.posts,372 tests:foundClass.tests,373 assign:foundClass.assignments374 });375 }376 });377});378 379 // class create and join380app.post("/createclass",(req,res)=>{381 Class.count({}, function( err, count){382 if(err){383 console.log(err);384 }else{385 Teacher.findOne({email:req.body.email}).populate('classes').exec((e,foundUser)=>{386 if(e){387 console.log(e);388 }else{389 if(foundUser.classes.some(e => e.name == req.body.classname)){390 res.render("teacher",{391 name:req.body.name,392 email: req.body.email,393 classes:foundUser.classes,394 error:"Classroom exists already!!"395 });396 }else{397 const newClass = new Class({398 teacher:req.body.name,399 name:req.body.classname,400 code:"SL"+String(count+1).padStart(4,'0')401 });402 foundUser.classes.push(newClass);403 foundUser.save();404 newClass.save(function(err){405 if (err) {406 console.log(err);407 } else {408 checkdue();409 res.render("class",{410 code:"SL"+String(count+1).padStart(4,'0'),411 name:req.body.name,412 classname:req.body.classname,413 email:foundUser.email,414 students:[],415 posts:[],416 tests:[],417 assign:[]418 });419 }420 }); 421 }422 }423 });424 } 425 });426});427app.post("/joinclass",(req,res)=>{428 Class.findOne({code:req.body.code})429 .populate('posts').populate('tests').populate('assignments').populate('students').430 exec((e,foundClass)=>{431 if(e){432 console.log(e);433 }else{434 Student.findOne({email:req.body.email}).populate('classes').exec((e,foundUser)=>{435 if(foundClass){436 if(e){437 console.log(e);438 }else{439 if(foundUser.classes.some(e => e.code == req.body.code)){440 res.render("sclass",{441 name:foundClass.teacher,442 email:req.body.email,443 classname:foundClass.name,444 students:foundClass.students,445 code:foundClass.code,446 posts:foundClass.posts,447 tests:foundClass.tests,448 assign:foundClass.assignments449 });450 }else{451 foundUser.classes.push(foundClass);452 foundUser.save();453 foundClass.students.push(foundUser);454 foundClass.save();455 let tests=foundClass.tests.map((i)=>{return i._id;});456 Test.find().where('_id').in(tests).exec((err, records) => {457 records.forEach(test=>{458 let d={459 name:foundUser.name,460 mark:0,461 id:foundUser._id,462 isSub:false463 };464 test.marks.push(d);465 test.save();466 });467 });468 let assignments=foundClass.assignments.map((i)=>{return i._id;}); 469 Assignment.find().where('_id').in(assignments).exec((err, records) => {470 records.forEach(a=>{471 let d={472 name:foundUser.name,473 mark:0,474 id:foundUser._id,475 isSub:false476 };477 a.marks.push(d);478 a.save();479 });480 });481 res.render("sclass",{482 name:foundClass.teacher,483 email:req.body.email,484 classname:foundClass.name,485 students:foundClass.students,486 code:foundClass.code,487 posts:foundClass.posts,488 tests:foundClass.tests,489 assign:foundClass.assignments490 });491 }492 }493 }else{494 res.render("student",{495 name:foundUser.name,496 email:foundUser.email,497 classes:foundUser.classes,498 error:"Class not found!!"499 });500 }501 });502 }503 });504});505 // post feature506app.post("/cpost",upload.array('files'),(req,res)=>{507 Class.findOne({code:req.body.code})508 .populate('posts').populate('tests').populate('assignments').populate('students').509 exec((e,foundClass)=>{510 if(e){511 console.log(e);512 }else{513 const newPost = new Post({514 author:req.body.author,515 title:req.body.title,516 description:req.body.desc,517 posttime: new Date().toString().slice(4,24)518 });519 if(req.files){520 newPost.files=req.files.map(a=>a.filename);521 }522 newPost.save((e)=>{523 if(e){524 console.log(e);525 }else{526 foundClass.posts.push(newPost);527 foundClass.save((e)=>{528 checkdue();529 res.render("class",{530 code:foundClass.code,531 name:foundClass.teacher,532 email:req.body.email,533 classname:foundClass.name,534 students:foundClass.students,535 posts:foundClass.posts,536 tests:foundClass.tests,537 assign:foundClass.assignments538 });539 });540 }541 });542 }543 });544});545app.post("/scpost",upload.array('files'),(req,res)=>{546 Class.findOne({code:req.body.code})547 .populate('posts').populate('tests').populate('assignments').populate('students').548 exec((e,foundClass)=>{549 if(e){550 console.log(e);551 }else{552 Student.findOne({email:req.body.email}).populate("classes").exec((e,foundUser)=>{553 if(e){554 console.log(e);555 }else{556 const newPost = new Post({557 author:foundUser.name,558 title:req.body.title,559 description:req.body.desc,560 posttime: new Date().toString().slice(4,24)561 });562 if(req.files){563 newPost.files=req.files.map(a=>a.filename);564 }565 newPost.save((e)=>{566 if(e){567 console.log(e);568 }else{569 foundClass.posts.push(newPost);570 foundClass.save((e)=>{571 res.render("sclass",{572 code:foundClass.code,573 name:foundClass.teacher,574 email:req.body.email,575 classname:foundClass.name,576 students:foundClass.students,577 posts:foundClass.posts,578 tests:foundClass.tests,579 assign:foundClass.assignments580 });581 });582 }583 });584 }585 });586 }587 });588});589 590 // test feature591app.post("/test",upload.array('files'),(req,res)=>{592 Class.findOne({code:req.body.code})593 .populate('posts').populate('tests').populate('assignments').populate('students').594 exec((e,foundClass)=>{595 if(e){596 console.log(e);597 }else{598 const newtest = new Test({599 title:req.body.title,600 description:req.body.desc,601 duetime: new Date(req.body.due).toLocaleDateString()+" "+new Date(req.body.due).toLocaleTimeString(), 602 maxmarks:req.body.mmark,603 status:"live"604 });605 foundClass.students.forEach(record=>{606 let d={607 name:record.name,608 mark:0,609 id:record._id,610 isSub:false611 };612 newtest.marks.push(d);613 });614 if(req.files){615 newtest.files=req.files.map(a=>a.filename);616 }617 newtest.save((e)=>{618 if(e){619 console.log(e);620 }else{621 foundClass.tests.push(newtest);622 foundClass.save((e)=>{623 checkdue();624 res.render("class",{625 code:foundClass.code,626 name:foundClass.teacher,627 email:req.body.email,628 classname:foundClass.name,629 students:foundClass.students,630 posts:foundClass.posts,631 tests:foundClass.tests,632 assign:foundClass.assignments633 });634 });635 }636 }); 637 }638 });639});640app.post("/testpage",(req,res)=>{641 Test.findOne({_id:req.body._id},function(e,foundTest){642 if(e){643 console.log(e);644 }else{645 res.render("test",{646 code:req.body.code,647 email:req.body.email,648 test:foundTest649 });650 }651 });652});653app.post("/stestpage",(req,res)=>{654 Test.findOne({_id:req.body._id},function(e,foundTest){655 if(e){656 console.log(e);657 }else{658 Student.findOne({email:req.body.email},function(e,foundStudent){659 var mark=(foundTest.marks.filter(m=>m.id==foundStudent._id))[0];660 var score=mark.mark==0?"pending":mark.mark;661 res.render("stest",{662 code:req.body.code,663 email:req.body.email,664 duetime:foundTest.duetime,665 maxmarks:foundTest.maxmarks,666 title:foundTest.title,667 description:foundTest.description,668 status:foundTest.status,669 files:foundTest.files,670 submitted:mark.isSub,671 score:score,672 _id:foundTest._id673 });674 });675 }676 });677});678app.post("/testansupdate",upload.array('files'),(req,res)=>{679 Test.findOne({_id:req.body._id},function(e,foundTest){680 if(e){681 console.log(e);682 }else{683 Student.findOne({email:req.body.email},function(e,foundStudent){684 for(let i=0;i<foundTest.marks.length;i++){685 if(foundTest.marks[i].id=foundStudent._id)686 {687 foundTest.marks[i].files=req.files.map(a=>a.filename);688 foundTest.marks[i].isSub=true;689 }690 }691 foundTest.save((e)=>{692 if(e){693 console.log(e);694 }else{695 res.render("stest",{696 code:req.body.code,697 email:req.body.email,698 duetime:foundTest.duetime,699 maxmarks:foundTest.maxmarks,700 title:foundTest.title,701 description:foundTest.description,702 status:foundTest.status,703 files:foundTest.files,704 submitted:true,705 score:"pending",706 _id:foundTest._id707 });708 }709 });710 });711 }712 }); 713});714app.post("/endtest",(req,res)=>{715 Test.findOneAndUpdate({_id:req.body._id}, {$set:{status:"ended"}},{new: true},(e, foundTest)=>{716 if(e){717 console.log(e);718 }else{719 res.render("test",{720 code:req.body.code,721 email:req.body.email,722 test:foundTest723 });724 }725 });726});727app.post("/markupdate",(req,res)=>{728 Test.findOne({_id:req.body._id},function(e,foundTest){729 if(e){730 console.log(e);731 }else{732 for(i=0;i<foundTest.marks.length;i++)733 foundTest.marks[i].mark=req.body[i];734 foundTest.save((e)=>{735 res.render("test",{736 code:req.body.code,737 email:req.body.email,738 test:foundTest739 });740 });741 }742 });743});744 // assignment feature745app.post("/assign",upload.array('files'),(req,res)=>{746 Class.findOne({code:req.body.code})747 .populate('posts').populate('tests').populate('assignments').populate('students').748 exec((e,foundClass)=>{749 if(e){750 console.log(e);751 }else{752 const newassignment = new Assignment({753 title:req.body.title,754 description:req.body.desc,755 duetime: new Date(req.body.due).toLocaleDateString()+" "+new Date(req.body.due).toLocaleTimeString(), 756 maxmarks:req.body.mmark,757 status:"live"758 });759 foundClass.students.forEach(record=>{760 let d={761 name:record.name,762 mark:0,763 id:record._id,764 isSub:false765 };766 newassignment.marks.push(d);767 });768 if(req.files){769 newassignment.files=req.files.map(a=>a.filename);770 }771 newassignment.save((e)=>{772 if(e){773 console.log(e);774 }else{775 foundClass.assignments.push(newassignment);776 foundClass.save((e)=>{777 checkdue();778 res.render("class",{779 code:foundClass.code,780 name:foundClass.teacher,781 email:req.body.email,782 classname:foundClass.name,783 students:foundClass.students,784 posts:foundClass.posts,785 tests:foundClass.tests,786 assign:foundClass.assignments787 });788 });789 }790 });791 }792 });793});794app.post("/assignpage",(req,res)=>{795 Assignment.findOne({_id:req.body._id},function(e,founda){796 if(e){797 console.log(e);798 }else{799 res.render("assign",{800 code:req.body.code,801 email:req.body.email,802 assign:founda803 });804 }805 });806});807app.post("/sassignpage",(req,res)=>{808 Assignment.findOne({_id:req.body._id},function(e,founda){809 if(e){810 console.log(e);811 }else{812 Student.findOne({email:req.body.email},function(e,foundStudent){813 var mark=(founda.marks.filter(m=>m.id==foundStudent._id))[0];814 var score=mark.mark==0?"pending":mark.mark;815 res.render("sassign",{816 code:req.body.code,817 email:req.body.email,818 duetime:founda.duetime,819 maxmarks:founda.maxmarks,820 title:founda.title,821 description:founda.description,822 status:founda.status,823 files:founda.files,824 submitted:mark.isSub,825 score:score,826 _id:founda._id827 });828 });829 }830 });831});832app.post("/assignansupdate",upload.array('files'),(req,res)=>{833 Assignment.findOne({_id:req.body._id},function(e,founda){834 if(e){835 console.log(e);836 }else{837 Student.findOne({email:req.body.email},function(e,foundStudent){838 for(let i=0;i<founda.marks.length;i++){839 if(founda.marks[i].id=foundStudent._id)840 {841 founda.marks[i].files=req.files.map(a=>a.filename);842 founda.marks[i].isSub=true;843 }844 }845 founda.save((e)=>{846 if(e){847 console.log(e);848 }else{849 res.render("sassign",{850 code:req.body.code,851 email:req.body.email,852 duetime:founda.duetime,853 maxmarks:founda.maxmarks,854 title:founda.title,855 description:founda.description,856 status:founda.status,857 files:founda.files,858 submitted:true,859 score:"pending",860 _id:founda._id861 });862 }863 });864 });865 }866 }); 867});868app.post("/endassign",(req,res)=>{869 Assignment.findOneAndUpdate({_id:req.body._id}, {$set:{status:"ended"}},{new: true},(e, founda)=>{870 if(e){871 console.log(e);872 }else{873 res.render("assign",{874 code:req.body.code,875 email:req.body.email,876 assign:founda877 });878 }879 });880});881app.post("/assignmarkupdate",(req,res)=>{882 Assignment.findOne({_id:req.body._id},function(e,founda){883 if(e){884 console.log(e);885 }else{886 for(i=0;i<founda.marks.length;i++)887 founda.marks[i].mark=req.body[i];888 founda.save((e)=>{889 res.render("assign",{890 code:req.body.code,891 email:req.body.email,892 assign:founda893 });894 });895 }896 });897});898 // timetable feature899app.post("/timetable",(req,res)=>{900 const ptype=req.body.type;901 if(ptype=="student"){902 Student.findOne({email:req.body.email},function(e,foundUser){903 if(e){904 console.log(e);905 }else{906 res.render("table",{907 email:req.body.email,908 type:ptype,909 periods:foundUser.periods910 });911 }912 });913 }else{914 Teacher.findOne({email:req.body.email},function(e,foundUser){915 if(e){916 console.log(e);917 }else{918 res.render("table",{919 email:req.body.email,920 type:ptype,921 periods:foundUser.periods922 });923 }924 });925 }926});927app.post("/tableupdate",(req,res)=>{928 const ptype=req.body.type;929 var periods=[["Monday"],["Tuesday"],["Wednesday"],["Thursday"],["Friday"]]930 for(var i=0,k=0;i<5;i++){931 for(var j=0;j<5;j++,k++){932 periods[i].push(req.body[k]);933 } 934 }935 if(ptype=="student"){936 Student.findOne({email:req.body.email},function(e,foundUser){937 if(e){938 console.log(e);939 }else{940 foundUser.periods=periods;941 foundUser.save();942 res.render("table",{943 email:req.body.email,944 type:ptype,945 periods:foundUser.periods946 });947 }948 });949 }else{950 Teacher.findOne({email:req.body.email},function(e,foundUser){951 if(e){952 console.log(e);953 }else{954 foundUser.periods=periods;955 foundUser.save();956 res.render("table",{957 email:req.body.email,958 type:ptype,959 periods:foundUser.periods960 });961 }962 });963 }964});965app.post("/tablehome",(req,res)=>{966 const ptype=req.body.type;967 if(ptype=="student"){968 Student.findOne({email:req.body.email}).populate('classes').exec(function(e,foundUser){969 if(e){970 console.log(e);971 }else{972 res.render("student",{973 name:foundUser.name,974 email:foundUser.email,975 classes:foundUser.classes,976 error:""977 }); 978 }979 });980 }else{981 Teacher.findOne({email:req.body.email}).populate('classes').exec(function(e,foundUser){982 if(e){983 console.log(e);984 }else{985 res.render("teacher",{986 name:foundUser.name,987 email:foundUser.email,988 classes:foundUser.classes,989 error:""990 }); 991 }992 });993 }994});995 //server start996app.listen(process.env.PORT || 3000,()=>{997 console.log("server is up and running");...
extract_tests.test.ts
Source:extract_tests.test.ts
1import { AstParser } from '~src/AstParser'2import { extractTests } from '~src/extracts/extract_tests'3import { InlineInput } from '~src/input/InlineInput'4describe('extractTests', () => {5 it('finds a top level test', async () => {6 const input = new InlineInput([7 `test("it finds this test", () => {8 expect(true).toBe(true)9 expect(false).not.toBe(true)10 })`,11 ])12 const [{ program }] = await AstParser.ANALYZER.parse(input)13 const [foundTest, ...others] = extractTests(program)14 expect(foundTest).not.toBeUndefined()15 expect(foundTest.test).toBe('it finds this test')16 expect(foundTest.description).toHaveLength(0)17 expect(foundTest.expectations).toHaveLength(2)18 expect(others).toHaveLength(0)19 })20 it('can extract the test code', async () => {21 const input = new InlineInput([22 `test("it finds this test", () => {23 const actual = 3 * 324 expect(actual).not.toBe(42)25 })`,26 ])27 const [{ program, source }] = await AstParser.ANALYZER.parse(input)28 const [foundTest, ...others] = extractTests(program)29 expect(foundTest).not.toBeUndefined()30 expect(foundTest.test).toBe('it finds this test')31 expect(foundTest.description).toHaveLength(0)32 expect(foundTest.expectations).toHaveLength(1)33 expect(others).toHaveLength(0)34 const [expectation] = foundTest.expectations35 const statementCode = expectation.statementCode(source)36 const expectCode = expectation.expectCode(source)37 const actualCode = expectation.actualCode(source)38 const testCode = foundTest.testCode(source)39 expect(statementCode).toBe('expect(actual).not.toBe(42)')40 expect(expectCode).toBe('.not.toBe(42)')41 expect(actualCode).toBe('actual')42 expect(testCode).toBe('const actual = 3 * 3\nexpect(actual).not.toBe(42)')43 })44 const methods = ['it', 'xit', 'test', 'xtest']45 const properties = ['skip', 'only']46 methods.forEach((method) => {47 it(`finds a top level test that uses "${method}"`, async () => {48 const input = new InlineInput([49 `${method}("it finds this ${method} test", () => {50 expect(true).toBe(true)51 })`,52 ])53 const [{ program }] = await AstParser.ANALYZER.parse(input)54 const [foundTest, ...others] = extractTests(program)55 expect(foundTest).not.toBeUndefined()56 expect(foundTest.test).toBe(`it finds this ${method} test`)57 expect(foundTest.description).toHaveLength(0)58 expect(foundTest.expectations).toHaveLength(1)59 expect(others).toHaveLength(0)60 })61 properties.forEach((property) => {62 it(`finds a top level test that uses "${method}.${property}"`, async () => {63 const input = new InlineInput([64 `${method}.${property}("it finds this ${method} test", () => {65 expect(true).toBe(true)66 })`,67 ])68 const [{ program }] = await AstParser.ANALYZER.parse(input)69 const [foundTest, ...others] = extractTests(program)70 expect(foundTest).not.toBeUndefined()71 expect(foundTest.test).toBe(`it finds this ${method} test`)72 expect(foundTest.description).toHaveLength(0)73 expect(foundTest.expectations).toHaveLength(1)74 expect(others).toHaveLength(0)75 })76 })77 })78 it('finds grouped tests', async () => {79 const input = new InlineInput([80 `describe("test group", () => {81 test("it finds this test", () => {82 expect(true).toBe(true)83 })84 test("it also finds this test", () => {85 expect(true).toBe(true)86 })87 })`,88 ])89 const [{ program }] = await AstParser.ANALYZER.parse(input)90 const [foundTest, foundAlsoTest, ...others] = extractTests(program)91 expect(foundTest).not.toBeUndefined()92 expect(foundTest.test).toBe('it finds this test')93 expect(foundTest.description).toStrictEqual(['test group'])94 expect(foundTest.expectations).toHaveLength(1)95 expect(foundAlsoTest).not.toBeUndefined()96 expect(foundAlsoTest.test).toBe('it also finds this test')97 expect(foundAlsoTest.description).toStrictEqual(['test group'])98 expect(foundAlsoTest.expectations).toHaveLength(1)99 expect(others).toHaveLength(0)100 })101 const groups = ['describe', 'xdescribe']102 groups.forEach((group) => {103 it(`finds grouped tests that uses "${group}"`, async () => {104 const input = new InlineInput([105 `${group}("test ${group} group", () => {106 test("it finds this test", () => {107 expect(true).toBe(true)108 })109 test("it also finds this test", () => {110 expect(true).toBe(true)111 })112 })`,113 ])114 const [{ program }] = await AstParser.ANALYZER.parse(input)115 const [foundTest, foundAlsoTest, ...others] = extractTests(program)116 expect(foundTest).not.toBeUndefined()117 expect(foundTest.test).toBe('it finds this test')118 expect(foundTest.description).toStrictEqual([`test ${group} group`])119 expect(foundTest.expectations).toHaveLength(1)120 expect(foundAlsoTest).not.toBeUndefined()121 expect(foundAlsoTest.test).toBe('it also finds this test')122 expect(foundAlsoTest.description).toStrictEqual([`test ${group} group`])123 expect(foundAlsoTest.expectations).toHaveLength(1)124 expect(others).toHaveLength(0)125 })126 properties.forEach((property) => {127 it(`finds grouped tests that uses "${group}.${property}"`, async () => {128 const input = new InlineInput([129 `${group}.${property}("test ${group} group", () => {130 test("it finds this test", () => {131 expect(true).toBe(true)132 })133 test("it also finds this test", () => {134 expect(true).toBe(true)135 })136 })`,137 ])138 const [{ program }] = await AstParser.ANALYZER.parse(input)139 const [foundTest, foundAlsoTest, ...others] = extractTests(program)140 expect(foundTest).not.toBeUndefined()141 expect(foundTest.test).toBe('it finds this test')142 expect(foundTest.description).toStrictEqual([`test ${group} group`])143 expect(foundTest.expectations).toHaveLength(1)144 expect(foundAlsoTest).not.toBeUndefined()145 expect(foundAlsoTest.test).toBe('it also finds this test')146 expect(foundAlsoTest.description).toStrictEqual([`test ${group} group`])147 expect(foundAlsoTest.expectations).toHaveLength(1)148 expect(others).toHaveLength(0)149 })150 })151 })152 it('finds deeply nested tests', async () => {153 const input = new InlineInput([154 `describe("test group", () => {155 test("it finds this test", () => {156 expect(true).toBe(true)157 })158 describe("nested group", () => {159 describe("deeply nested group", () => {160 test("it also finds this test", () => {161 expect(true).toBe(true)162 })163 })164 test("it finds this last test", () => {165 expect(true).toBe(true)166 })167 })168 })`,169 ])170 const [{ program }] = await AstParser.ANALYZER.parse(input)171 const [foundTest, foundAlsoTest, foundLastTest, ...others] = extractTests(172 program173 )174 expect(foundTest).not.toBeUndefined()175 expect(foundTest.test).toBe('it finds this test')176 expect(foundTest.description).toStrictEqual(['test group'])177 expect(foundTest.expectations).toHaveLength(1)178 expect(foundAlsoTest).not.toBeUndefined()179 expect(foundAlsoTest.test).toBe('it also finds this test')180 expect(foundAlsoTest.description).toStrictEqual([181 'test group',182 'nested group',183 'deeply nested group',184 ])185 expect(foundAlsoTest.expectations).toHaveLength(1)186 expect(foundLastTest).not.toBeUndefined()187 expect(foundLastTest.test).toBe('it finds this last test')188 expect(foundLastTest.description).toStrictEqual([189 'test group',190 'nested group',191 ])192 expect(foundLastTest.expectations).toHaveLength(1)193 expect(others).toHaveLength(0)194 })...
test-model.service.ts
Source:test-model.service.ts
1import { Injectable, Logger } from '@nestjs/common';2import { TestRepositoryService } from '../database/test-repository.service';3import { TestTemplateService } from '../test-template/test-template.service';4import { TestState, Test } from 'src/models/execution/test';5import { TestStateMachine } from './impl/test-state-machine';6import { PostTest } from 'src/models/execution/post-test';7import {8 TestExecutionTurn,9 TestExecutionEdge,10} from 'src/models/execution/test.execution';11import { RedisDatabase } from '../database/redis.database';12import { RedisConstants } from 'src/constants/constants';13@Injectable()14export class TestService {15 private readonly logger = new Logger(TestService.name);16 constructor(17 private readonly testRepositoryService: TestRepositoryService,18 private readonly testTemplateService: TestTemplateService,19 private readonly redisDatabase: RedisDatabase,20 ) {}21 async postTest(postTest: PostTest): Promise<boolean> {22 this.logger.log(`New request - posting Test: ${JSON.stringify(postTest)}`);23 const newTest = postTest.test;24 const validationTemplateResponse = await this.testTemplateService.validateTemplate(25 newTest.template,26 );27 if (!validationTemplateResponse.isValid) {28 throw new Error(validationTemplateResponse.causeIfIsNotValid);29 }30 newTest.state = TestState.IDLE;31 const wasCreated = await this.testRepositoryService.save(newTest);32 this.logger.log(`Was Test created? ${JSON.stringify(wasCreated)}`);33 return wasCreated;34 }35 async changeState(testCode: string, newState: TestState) {36 try {37 const foundTest = await this.foundTestOrThrowError(testCode);38 const isAlreadyInThisState = foundTest.state === newState;39 if (isAlreadyInThisState)40 throw new Error(`Test ${testCode} is already ${newState}`);41 TestStateMachine.change(foundTest, newState);42 await this.updateTest(foundTest);43 } catch (error) {44 throw new Error(`Error when start Test: ${error.message}`);45 }46 }47 async updateTest(test: Test): Promise<boolean> {48 const updatedTest = await this.testRepositoryService.save(test);49 await this.publishTestState(test);50 return updatedTest;51 }52 public getLastExecutionTurn(test: Test): TestExecutionTurn {53 if (!test) throw new Error(`Can't get last execution turn of null test`);54 if (!test.testExecution) return null;55 const testExecution = test.testExecution;56 const turns = testExecution.turns;57 if (!turns) return null;58 return turns.sort((x, y) => x.number - y.number).reverse()[0];59 }60 public getLastExecutionEdge(61 testExecutionTurn: TestExecutionTurn,62 ): TestExecutionEdge {63 if (!testExecutionTurn) return null;64 const executionEdges = testExecutionTurn.executionEdges;65 if (!executionEdges || executionEdges.length <= 0) return null;66 return executionEdges67 .sort((x, y) => x.edge.sequence - y.edge.sequence)68 .reverse()[0];69 }70 public async foundTestOrThrowError(testCode: string): Promise<Test> {71 const foundTest = await this.testRepositoryService.findOne(testCode);72 if (!foundTest) throw new Error(`Can't find Test with code ${testCode}`);73 return foundTest;74 }75 public async publishTestState(test: Test) {76 if (!test) throw new Error(`Can't publish state for a null test`);77 this.logger.log(`Publishing in update state channel...`);78 const redisPubClient = this.redisDatabase.getPublisherClient();79 redisPubClient.publish(80 RedisConstants.TEST_UPDATE_STATE_CHANNEL,81 JSON.stringify(test),82 );83 }...
Using AI Code Generation
1var strykerParent = require('stryker-parent');2strykerParent.foundTest();3var strykerParent = require('stryker-parent');4strykerParent.foundTest();5var strykerParent = require('stryker-parent');6strykerParent.foundTest();7var strykerParent = require('stryker-parent');8strykerParent.foundTest();9var strykerParent = require('stryker-parent');10strykerParent.foundTest();11var strykerParent = require('stryker-parent');12strykerParent.foundTest();13var strykerParent = require('stryker-parent');14strykerParent.foundTest();15var strykerParent = require('stryker-parent');16strykerParent.foundTest();17var strykerParent = require('stryker-parent');18strykerParent.foundTest();19var strykerParent = require('stryker-parent');20strykerParent.foundTest();21var strykerParent = require('stryker-parent');22strykerParent.foundTest();23var strykerParent = require('stryker-parent');24strykerParent.foundTest();25var strykerParent = require('stryker-parent');26strykerParent.foundTest();
Using AI Code Generation
1var foundTest = require('stryker-parent').foundTest;2foundTest('test.js');3var foundTest = require('stryker-parent').foundTest;4foundTest('test.js');5module.exports = {6 foundTest: function (name) {7 console.log('Found test ' + name);8 }9};10module.exports = {11 foundTest: function (name) {12 console.log('Found test ' + name);13 }14};15{16}17{18}19var foundTest = require('./index.js').foundTest;20foundTest('test.js');21var foundTest = require('./index.js').foundTest;22foundTest('tes
Using AI Code Generation
1var foundTest = require('stryker-parent').foundTest;2var foundTest = require('stryker-parent').foundTest;3var foundTest = require('stryker-parent').foundTest;4var foundTest = require('stryker-parent').foundTest;5var foundTest = require('stryker-parent').foundTest;6var foundTest = require('stryker-parent').foundTest;7var foundTest = require('stryker-parent').foundTest;8var foundTest = require('stryker-parent').foundTest;9var foundTest = require('stryker-parent').foundTest;10var foundTest = require('stryker-parent').foundTest;11var foundTest = require('stryker-parent').foundTest;12var foundTest = require('stryker-parent').foundTest;13var foundTest = require('stryker-parent').foundTest;14var foundTest = require('stryker-parent').foundTest;15var foundTest = require('stryker-parent').foundTest;16var foundTest = require('stryker-parent').foundTest;17var foundTest = require('stryker-parent').foundTest;18var foundTest = require('stryker-parent
Using AI Code Generation
1var stryker = require('stryker-parent');2var foundTest = stryker.foundTest;3var stryker = require('stryker-child');4var foundTest = stryker.foundTest;5var stryker = require('stryker-parent');6var foundTest = stryker.foundTest;7var stryker = require('stryker-child');8var foundTest = stryker.foundTest;9var stryker = require('stryker-parent');10var foundTest = stryker.foundTest;11var stryker = require('stryker-child');12var foundTest = stryker.foundTest;13var stryker = require('stryker-parent');14var foundTest = stryker.foundTest;15var stryker = require('stryker-child');16var foundTest = stryker.foundTest;17var stryker = require('stryker-parent');18var foundTest = stryker.foundTest;19var stryker = require('stryker-child');20var foundTest = stryker.foundTest;21var stryker = require('stryker-parent');22var foundTest = stryker.foundTest;23var stryker = require('stryker-child');24var foundTest = stryker.foundTest;25var stryker = require('stryker-parent');26var foundTest = stryker.foundTest;27var stryker = require('stry
Using AI Code Generation
1var stryker = require('stryker-parent');2var test = stryker.foundTest();3console.log(test);4var stryker = require('stryker-parent');5var test = stryker.foundTest();6console.log(test);
Using AI Code Generation
1function foundTest() {2}3function foundTest() {4}5function foundTest() {6}7module.exports = function(config) {8 config.set({9 });10};11module.exports = function(config) {12 config.set({13 });14};15module.exports = function(config) {16 config.set({17 });18};19module.exports = function(config) {20 config.set({
Using AI Code Generation
1var foundTest = require('stryker-parent').foundTest;2var found = foundTest('test');3console.log('found: ' + found);4module.exports.foundTest = function (test) {5 return test === 'test';6};7var plugins = loadPlugins('stryker-*', 'stryker-*', 'plugin', function (pluginName) {8 console.log('Loading plugin ' + pluginName);9});10function loadPlugins(pluginNamePattern, pluginPrefix, pluginType, log) {11 var plugins = [];12 var pluginNames = glob.sync(pluginNamePattern, { cwd: path.join(__dirname, '..', '..') });13 pluginNames.forEach(function (pluginName) {14 var plugin = require(pluginName);15 if (plugin[pluginType]) {16 plugins.push(plugin[pluginType]);17 log(pluginName);18 }19 });20 return plugins;21}22function require(pluginName) {23 var pluginPath = path.join(pluginName, pluginPrefix + pluginName);24 return require(pluginPath);25}26function require(pluginPath) {27 return require(pluginPath);28}29function require(pluginPath) {30 return require(pluginPath);31}32function require(pluginPath) {33 return require(pluginPath);34}35function require(pluginPath) {36 return require(pluginPath);37}38function require(pluginPath) {39 return require(pluginPath);40}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!