How to use Warn method of js Package

Best K6 code snippet using js.Warn

statistics.go

Source:statistics.go Github

copy

Full Screen

...40 fallthrough41 case "day":42 res, err := r.StatisticsDao.GetCourseStatsWeekdays(cid)43 if err != nil {44 log.WithError(err).WithField("courseId", cid).Warn("GetCourseStatsWeekdays failed")45 c.AbortWithStatus(http.StatusInternalServerError)46 return47 }48 resp := chartJs{49 ChartType: "bar",50 Data: chartJsData{Datasets: []chartJsDataset{newChartJsDataset()}},51 Options: newChartJsOptions(),52 }53 resp.Data.Datasets[0].Label = "Sum(viewers)"54 resp.Data.Datasets[0].Data = res55 c.JSON(http.StatusOK, resp)56 case "hour":57 res, err := r.StatisticsDao.GetCourseStatsHourly(cid)58 if err != nil {59 log.WithError(err).WithField("courseId", cid).Warn("GetCourseStatsHourly failed")60 c.AbortWithStatus(http.StatusInternalServerError)61 return62 }63 resp := chartJs{64 ChartType: "bar",65 Data: chartJsData{Datasets: []chartJsDataset{newChartJsDataset()}},66 Options: newChartJsOptions(),67 }68 resp.Data.Datasets[0].Label = "Sum(viewers)"69 resp.Data.Datasets[0].Data = res70 c.JSON(http.StatusOK, resp)71 case "activity-live":72 resLive, err := r.StatisticsDao.GetStudentActivityCourseStats(cid, true)73 if err != nil {74 log.WithError(err).WithField("courseId", cid).Warn("GetCourseStatsLive failed")75 c.AbortWithStatus(http.StatusInternalServerError)76 return77 }78 resp := chartJs{79 ChartType: "line",80 Data: chartJsData{Datasets: []chartJsDataset{newChartJsDataset()}},81 Options: newChartJsOptions(),82 }83 resp.Data.Datasets[0].Label = "Live"84 resp.Data.Datasets[0].Data = resLive85 resp.Data.Datasets[0].BorderColor = "#d12a5c"86 resp.Data.Datasets[0].BackgroundColor = ""87 c.JSON(http.StatusOK, resp)88 case "activity-vod":89 resVod, err := r.StatisticsDao.GetStudentActivityCourseStats(cid, false)90 if err != nil {91 log.WithError(err).WithField("courseId", cid).Warn("GetCourseStatsVod failed")92 c.AbortWithStatus(http.StatusInternalServerError)93 return94 }95 resp := chartJs{96 ChartType: "line",97 Data: chartJsData{Datasets: []chartJsDataset{newChartJsDataset()}},98 Options: newChartJsOptions(),99 }100 resp.Data.Datasets[0].Label = "VoD"101 resp.Data.Datasets[0].Data = resVod102 resp.Data.Datasets[0].BorderColor = "#2a7dd1"103 resp.Data.Datasets[0].BackgroundColor = ""104 c.JSON(http.StatusOK, resp)105 case "numStudents":106 res, err := r.StatisticsDao.GetCourseNumStudents(cid)107 if err != nil {108 log.WithError(err).WithField("courseId", cid).Warn("GetCourseNumStudents failed")109 c.AbortWithStatus(http.StatusInternalServerError)110 } else {111 c.JSON(http.StatusOK, gin.H{"res": res})112 }113 case "vodViews":114 res, err := r.StatisticsDao.GetCourseNumVodViews(cid)115 if err != nil {116 log.WithError(err).WithField("courseId", cid).Warn("GetCourseNumVodViews failed")117 c.AbortWithStatus(http.StatusInternalServerError)118 } else {119 c.JSON(http.StatusOK, gin.H{"res": res})120 }121 case "liveViews":122 res, err := r.StatisticsDao.GetCourseNumLiveViews(cid)123 if err != nil {124 log.WithError(err).WithField("courseId", cid).Warn("GetCourseNumLiveViews failed")125 c.AbortWithStatus(http.StatusInternalServerError)126 } else {127 c.JSON(http.StatusOK, gin.H{"res": res})128 }129 case "allDays":130 {131 res, err := r.StatisticsDao.GetCourseNumVodViewsPerDay(cid)132 if err != nil {133 log.WithError(err).WithField("courseId", cid).Warn("GetCourseNumLiveViews failed")134 c.AbortWithStatus(http.StatusInternalServerError)135 } else {136 resp := chartJs{137 ChartType: "bar",138 Data: chartJsData{Datasets: []chartJsDataset{newChartJsDataset()}},139 Options: newChartJsOptions(),140 }141 resp.Data.Datasets[0].Label = "views"142 resp.Data.Datasets[0].Data = res143 resp.Data.Datasets[0].BackgroundColor = "#d12a5c"144 c.JSON(http.StatusOK, resp)145 }146 }147 default:148 c.AbortWithStatus(http.StatusBadRequest)149 }150}151func (r coursesRoutes) exportStats(c *gin.Context) {152 ctx, _ := c.Get("TUMLiveContext")153 var req statExportReq154 if c.ShouldBindQuery(&req) != nil {155 c.AbortWithStatus(http.StatusBadRequest)156 }157 var cid uint158 // check if request is for server -> validate159 cidFromContext := c.Param("courseId")160 if cidFromContext == "0" {161 if ctx.(tools.TUMLiveContext).User.Role != model.AdminType {162 c.AbortWithStatus(http.StatusForbidden)163 return164 }165 cid = 0166 } else { // use course from context167 cid = ctx.(tools.TUMLiveContext).Course.ID168 }169 if req.Format != "json" && req.Format != "csv" {170 log.WithField("courseId", cid).Warn("exportStats failed, invalid format")171 c.AbortWithStatus(http.StatusBadRequest)172 return173 }174 result := tools.ExportStatsContainer{}175 for _, interval := range req.Interval {176 switch interval {177 case "week":178 case "day":179 res, err := r.StatisticsDao.GetCourseStatsWeekdays(cid)180 if err != nil {181 log.WithError(err).WithField("courseId", cid).Warn("GetCourseStatsWeekdays failed")182 }183 result = result.AddDataEntry(&tools.ExportDataEntry{184 Name: interval,185 XName: "Weekday",186 YName: "Sum(viewers)",187 Data: res,188 })189 case "hour":190 res, err := r.StatisticsDao.GetCourseStatsHourly(cid)191 if err != nil {192 log.WithError(err).WithField("courseId", cid).Warn("GetCourseStatsHourly failed")193 }194 result = result.AddDataEntry(&tools.ExportDataEntry{195 Name: interval,196 XName: "Hour",197 YName: "Sum(viewers)",198 Data: res,199 })200 case "activity-live":201 resLive, err := r.StatisticsDao.GetStudentActivityCourseStats(cid, true)202 if err != nil {203 log.WithError(err).WithField("courseId", cid).Warn("GetStudentActivityCourseStats failed")204 }205 result = result.AddDataEntry(&tools.ExportDataEntry{206 Name: interval,207 XName: "Week",208 YName: "Live",209 Data: resLive,210 })211 case "activity-vod":212 resVod, err := r.StatisticsDao.GetStudentActivityCourseStats(cid, false)213 if err != nil {214 log.WithError(err).WithField("courseId", cid).Warn("GetStudentActivityCourseStats failed")215 }216 result = result.AddDataEntry(&tools.ExportDataEntry{217 Name: interval,218 XName: "Week",219 YName: "VoD",220 Data: resVod,221 })222 case "allDays":223 res, err := r.StatisticsDao.GetCourseNumVodViewsPerDay(cid)224 if err != nil {225 log.WithError(err).WithField("courseId", cid).Warn("GetCourseNumVodViewsPerDay failed")226 }227 result = result.AddDataEntry(&tools.ExportDataEntry{228 Name: interval,229 XName: "Week",230 YName: "VoD",231 Data: res,232 })233 case "quickStats":234 var quickStats []dao.Stat235 numStudents, err := r.StatisticsDao.GetCourseNumStudents(cid)236 if err != nil {237 log.WithError(err).WithField("courseId", cid).Warn("GetCourseNumStudents failed")238 } else {239 quickStats = append(quickStats, dao.Stat{X: "Enrolled Students", Y: int(numStudents)})240 }241 vodViews, err := r.StatisticsDao.GetCourseNumVodViews(cid)242 if err != nil {243 log.WithError(err).WithField("courseId", cid).Warn("GetCourseNumVodViews failed")244 } else {245 quickStats = append(quickStats, dao.Stat{X: "Vod Views", Y: int(vodViews)})246 }247 liveViews, err := r.StatisticsDao.GetCourseNumLiveViews(cid)248 if err != nil {249 log.WithError(err).WithField("courseId", cid).Warn("GetCourseNumLiveViews failed")250 } else {251 quickStats = append(quickStats, dao.Stat{X: "Live Views", Y: int(liveViews)})252 }253 result = result.AddDataEntry(&tools.ExportDataEntry{254 Name: interval,255 XName: "Property",256 YName: "Value",257 Data: quickStats,258 })259 default:260 log.WithField("courseId", cid).Warn("Invalid export interval")261 }262 }263 if req.Format == "json" {264 jsonResult, err := json.Marshal(result.ExportJson())265 if err != nil {266 log.WithError(err).WithField("courseId", cid).Warn("json.Marshal failed for stats export")267 c.AbortWithStatus(http.StatusInternalServerError)268 return269 }270 c.Header("Content-Disposition", "attachment; filename=course-"+strconv.Itoa(int(cid))+"-stats.json")271 c.Data(http.StatusOK, "application/octet-stream", jsonResult)272 } else {273 c.Header("Content-Disposition", "attachment; filename=course-"+strconv.Itoa(int(cid))+"-stats.csv")274 c.Data(http.StatusOK, "application/octet-stream", []byte(result.ExportCsv()))275 }276}277//278// Chart.js datastructures:279//280type chartJsData struct {...

Full Screen

Full Screen

main.go

Source:main.go Github

copy

Full Screen

...27}28func checkSystemdUnit() (output string, perfdata PerfdataCollection, errs map[string]error) {29 cli := flag.NewFlagSet(os.Args[0], flag.ContinueOnError)30 unit := cli.String("unit", "", "e.g. icinga2.service")31 thresholdsWarn := thresholds{}32 thresholdsCrit := thresholds{}33 var jsWarn, jsCrit assertions34 cli.Var(thresholdsWarn, "warn", "e.g. NRestarts(@~:42)")35 cli.Var(thresholdsCrit, "crit", "e.g. NRestarts(@~:42)")36 cli.Var(&jsWarn, "js-warn", `e.g. ActiveState==="active"`)37 cli.Var(&jsCrit, "js-crit", `e.g. ActiveState==="active"`)38 if errCli := cli.Parse(os.Args[1:]); errCli != nil {39 os.Exit(3)40 }41 if *unit == "" {42 fmt.Fprintln(os.Stderr, "-unit missing")43 cli.Usage()44 os.Exit(3)45 }46 dBus, errConn := dbus.New()47 if errConn != nil {48 errs = map[string]error{"D-Bus": errConn}49 return50 }51 defer dBus.Close()52 props, errProps := dBus.GetAllProperties(*unit)53 if errProps != nil {54 errs = map[string]error{"D-Bus": errProps}55 return56 }57 vm := js.New()58 for k, v := range props {59 if num, signed, isNum := number2float(v); isNum {60 var uom string61 if strings.HasSuffix(k, "USec") {62 uom = "us"63 }64 perfdata = append(perfdata, Perfdata{65 Label: k,66 UOM: uom,67 Value: num,68 Warn: thresholdsWarn[k],69 Crit: thresholdsCrit[k],70 Min: OptionalNumber{!signed, 0},71 })72 delete(thresholdsWarn, k)73 delete(thresholdsCrit, k)74 }75 vm.Set(k, v)76 }77 if len(thresholdsWarn) > 0 || len(thresholdsCrit) > 0 {78 perfdata = nil79 nosuch := map[string]struct{}{}80 nonum := map[string]struct{}{}81 for _, t := range [2]thresholds{thresholdsWarn, thresholdsCrit} {82 for k := range t {83 if _, hasProp := props[k]; hasProp {84 nonum[k] = struct{}{}85 } else {86 nosuch[k] = struct{}{}87 }88 }89 }90 errs = make(map[string]error, len(nosuch)+len(nonum))91 if len(nosuch) > 0 {92 err := errors.New("no such unit property")93 for k := range nosuch {94 errs[fmt.Sprintf("threshold %q", k)] = err95 }96 }97 for k := range nonum {98 v := props[k]99 typ := reflect.TypeOf(v)100 var typeName string101 if typ == nil {102 typeName = "nil"103 } else {104 typeName = typ.Name()105 }106 errs[fmt.Sprintf("threshold %q", k)] = fmt.Errorf("not a number: %s(%#v)", typeName, v)107 }108 return109 }110 var failedJs []string = nil111 var jsWarnFailed uint64 = 0112 var jsCritFailed uint64 = 0113 for _, jw := range jsWarn {114 if res, errJs := vm.Eval(jw.compiled); errJs != nil {115 if errs == nil {116 errs = map[string]error{}117 }118 errs[fmt.Sprintf("script %q", jw.raw)] = errJs119 } else if boool, errBool := res.ToBoolean(); errBool != nil || !boool {120 failedJs = append(failedJs, jw.raw)121 jsWarnFailed++122 }123 }124 for _, jc := range jsCrit {125 if res, errJs := vm.Eval(jc.compiled); errJs != nil {126 if errs == nil {127 errs = map[string]error{}128 }129 errs[fmt.Sprintf("script %q", jc.raw)] = errJs130 } else if boool, errBool := res.ToBoolean(); errBool != nil || !boool {131 failedJs = append(failedJs, jc.raw)132 jsCritFailed++133 }134 }135 if errs != nil {136 perfdata = nil137 return138 }139 var out bytes.Buffer140 if len(failedJs) > 0 {141 out.Write([]byte(`<p><b>Some JS assertions failed:</b></p><ul>`))142 for _, fj := range failedJs {143 out.Write([]byte(`<li style="font-family: monospace; white-space: pre;">`))144 out.Write([]byte(html.EscapeString(fj)))145 out.Write([]byte(`</li>`))146 }147 out.Write([]byte(`</ul>`))148 }149 var failedThresholds []*Perfdata = nil150 for i := range perfdata {151 if pd := &perfdata[i]; pd.GetStatus() != Ok {152 failedThresholds = append(failedThresholds, pd)153 }154 }155 perfdata = append(perfdata, Perfdata{156 Label: "js_warn",157 Value: float64(jsWarnFailed),158 Warn: OptionalThreshold{true, false, 0, 0},159 Min: OptionalNumber{true, 0},160 Max: OptionalNumber{true, float64(len(jsWarn))},161 })162 perfdata = append(perfdata, Perfdata{163 Label: "js_crit",164 Value: float64(jsCritFailed),165 Crit: OptionalThreshold{true, false, 0, 0},166 Min: OptionalNumber{true, 0},167 Max: OptionalNumber{true, float64(len(jsCrit))},168 })169 if failedThresholds != nil {170 sort.Slice(failedThresholds, func(i, j int) bool {171 lhs := failedThresholds[i]172 rhs := failedThresholds[j]173 lhss := lhs.GetStatus()174 rhss := rhs.GetStatus()175 if lhss == rhss {176 return lhs.Label < rhs.Label177 } else {178 return lhss > rhss179 }180 })181 out.Write([]byte(`<p><b>Some threshold assertions failed:</b></p><ul>`))182 colors := map[PerfdataStatus]string{Warning: "770", Critical: "700"}183 for _, ft := range failedThresholds {184 fmt.Fprintf(185 &out,186 `<li style="color: #%s;">%s = %s</li>`,187 colors[ft.GetStatus()],188 ft.Label,189 strconv.FormatFloat(ft.Value, 'f', -1, 64),190 )191 }192 out.Write([]byte(`</ul>`))193 }194 if out.Len() < 1 {195 out.Write([]byte(`<p style="color: #070;">OK</p>`))196 }...

Full Screen

Full Screen

runtime_javascript_logger_test.go

Source:runtime_javascript_logger_test.go Github

copy

Full Screen

...41 loggedLog := logs.TakeAll()[0]42 assert.Equal(t, loggedLog.Level, zap.InfoLevel)43 assert.Equal(t, loggedLog.Message, "info log")44}45func TestJsLoggerWarn(t *testing.T) {46 r := goja.New()47 observer, logs := observer.New(zap.WarnLevel)48 obs := zap.New(observer)49 jsLoggerInst, err := NewJsLogger(r, obs)50 if err != nil {51 t.Error("Failed to instantiate jsLogger")52 }53 r.Set("logger", jsLoggerInst)54 SCRIPT := `55var s = 'warn';56logger.warn('%s log', s);57`58 _, err = r.RunString(SCRIPT)59 if err != nil {60 t.Error("Failed to run JS script")61 }62 assert.Equal(t, 1, logs.Len())63 loggedLog := logs.TakeAll()[0]64 assert.Equal(t, loggedLog.Level, zap.WarnLevel)65 assert.Equal(t, loggedLog.Message, "warn log")66}67func TestJsLoggerError(t *testing.T) {68 r := goja.New()69 observer, logs := observer.New(zap.ErrorLevel)70 obs := zap.New(observer)71 jsLoggerInst, err := NewJsLogger(r, obs)72 if err != nil {73 t.Error("Failed to instantiate jsLogger")74 }75 r.Set("logger", jsLoggerInst)76 SCRIPT := `77var s = 'error';78logger.error('%s log', s);...

Full Screen

Full Screen

Warn

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 js.Global.Get("console").Call("warn", "Hello World!")4}5import (6func main() {7 js.Global.Get("console").Call("log", "Hello World!")8}9import (10func main() {11 js.Global.Get("console").Call("error", "Hello World!")12}13import (14func main() {15 js.Global.Get("console").Call("info", "Hello World!")16}17import (18func main() {19 js.Global.Get("console").Call("debug", "Hello World!")20}21import (22func main() {23 js.Global.Get("console").Call("time", "Hello World!")24}25import (26func main() {27 js.Global.Get("console").Call("timeEnd", "Hello World!")28}29import (30func main() {31 js.Global.Get("console").Call("dir", "Hello World!")32}33import (34func main() {35 js.Global.Get("console").Call("dirxml", "Hello World!")36}

Full Screen

Full Screen

Warn

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 vm := otto.New()4 vm.Set("log", log.New(os.Stdout, "", 0))5 vm.Run(`6 log.Warn("Hello, World!")7}8import (9func main() {10 vm := otto.New()11 vm.Set("log", log.New(os.Stdout, "", 0))12 vm.Run(`13 log.Warn("Hello, World!")14}15var log = require('log');16log.Warn = function(msg) {17 log.warn(msg);18};19module.exports = log;20import (21func main() {22 vm := otto.New()23 vm.Import(new(log.Logger))24 vm.Run(`25 log.Warn("Hello, World!")26}27import (28func main() {29 vm := otto.New()30 vm.Import(new(log.Logger))31 vm.Run(`32 log.Warn("Hello, World!")33}

Full Screen

Full Screen

Warn

Using AI Code Generation

copy

Full Screen

1var js = require("js");2js.warn("Hello World");3var js = require("js");4js.warn("Hello World");5var js = require("js");6js.warn("Hello World");7var js = require("js");8js.warn("Hello World");9var js = require("js");10js.warn("Hello World");11var js = require("js");12js.warn("Hello World");13var js = require("js");14js.warn("Hello World");15var js = require("js");16js.warn("Hello World");17var js = require("js");18js.warn("Hello World");19var js = require("js");20js.warn("Hello World");21var js = require("js");22js.warn("Hello World");23var js = require("js");24js.warn("Hello World");25var js = require("js");26js.warn("Hello World");27var js = require("js");28js.warn("Hello World");29var js = require("js");30js.warn("Hello World");31var js = require("js");32js.warn("Hello World");33var js = require("js");34js.warn("Hello World");

Full Screen

Full Screen

Warn

Using AI Code Generation

copy

Full Screen

1func main(){2 js.Warn("Hello World")3}4func main(){5 js.Error("Hello World")6}7func main(){8 js.Log("Hello World")9}10func main(){11 js.Info("Hello World")12}13func main(){14 js.Debug("Hello World")15}16func main(){17 js.Assert(true, "Hello World")18}19func main(){20 js.Time("Hello World")21}22func main(){23 js.TimeEnd("Hello World")24}25func main(){26 js.TimeLog("Hello World")27}28func main(){29 js.Trace("Hello World")30}

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run K6 automation tests on LambdaTest cloud grid

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

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful