-
Notifications
You must be signed in to change notification settings - Fork 35
/
main_test.go
789 lines (717 loc) · 17.8 KB
/
main_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
package main
import (
"bytes"
"errors"
"flag"
"fmt"
"os"
"path"
"path/filepath"
"testing"
e "github.com/britannic/blacklist/internal/edgeos"
"github.com/britannic/mflag"
. "github.com/smartystreets/goconvey/convey"
)
func init() {
/*
The default failure mode is FailureHalts, which causes test execution
within a `Convey` block to halt at the first failure. You could use
that mode if the test were re-worked to aggregate all results into
a collection that was verified after all goroutines have finished.
But, as the code stands, you need to use the FailureContinues mode.
The following line sets the failure mode for all tests in the package:
*/
SetDefaultFailureMode(FailureContinues)
}
var update = flag.Bool("update", false, "update .golden files")
func readGolden(t *testing.T, name string) []byte {
path := filepath.Join("testdata", name+".golden") // relative path
bytes, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
return bytes
}
func writeGolden(t *testing.T, actual []byte, name string) error {
golden := filepath.Join("testdata", name+".golden")
if *update {
return os.WriteFile(golden, actual, 0o644)
}
return nil
}
func (o *opts) String() string {
var s string
o.VisitAll(func(f *mflag.Flag) {
s += fmt.Sprintf(" -%s", f.Name) // Two spaces before -; see next two comments.
name, usage := mflag.UnquoteUsage(f)
if len(name) > 0 {
s += " " + name
}
// Boolean flags of one ASCII letter are so common we
// treat them specially, putting their usage on the same line.
if len(s) <= 4 { // space, space, '-', 'x'.
s += "\t"
} else {
// Four spaces before the tab triggers good alignment
// for both 4- and 8-space tab stops.
s += "\n \t"
}
s += usage
if !mflag.IsZeroValue(f, f.DefValue) {
if _, ok := f.Value.(*mflag.StringValue); ok {
// put quotes on the value
s += fmt.Sprintf(" (default %q)", f.DefValue)
} else {
s += fmt.Sprintf(" (default %v)", f.DefValue)
}
}
s = fmt.Sprint(s, "\n")
})
return s
}
func TestLogFatalf(t *testing.T) {
var (
act string
exp = "Something fatal happened!"
)
exitCmd = func(int) {}
logCritf = func(f string, args ...interface{}) {
act = fmt.Sprintf(f, args...)
}
Convey("Testing LogFatalf", t, func() {
logFatalf("%v", exp)
So(act, ShouldEqual, exp)
})
}
func TestMain(t *testing.T) {
origArgs := os.Args
Convey("Testing main()", t, func() {
var (
act string
actReloadDNS string
prog = path.Base(os.Args[0])
prfx = fmt.Sprintf("%s: ", prog)
)
exitCmd = func(int) {}
logFatalf = func(f string, args ...interface{}) {
act = fmt.Sprintf(f, args...)
}
logPrintf = func(f string, vals ...interface{}) {
actReloadDNS = fmt.Sprintf(f, vals...)
}
screenLog(prfx)
main()
So(act, ShouldNotBeNil)
So(actReloadDNS, ShouldNotBeNil)
Convey("Testing main() with configuration file load", func() {
act = ""
os.Args = []string{prog, "-convey-json", "-f", "github.com/britannic/blacklist/internal/testdata/config.erx.boot"}
main()
So(act, ShouldBeEmpty)
os.Args = origArgs
})
// Convey("Testing main() with non-existent configuration file load", func() {
// var s string
// os.Args = []string{prog, "-convey-json", "-f", "github.com/britannic/blacklist/internal/testdata/config.bad.boot"}
// logFatalf = func(f string, args ...interface{}) {
// s = fmt.Sprintf(f, args...)
// }
// main()
// So(s, ShouldEqual, "cannot read configuration file internal/testdata/config.bad.boot!")
// os.Args = origArgs
// })
Convey("Testing main() with failed initEnv()", func() {
var (
act = new(bytes.Buffer)
exp = ""
)
initEnvirons = func() (env *e.Config, err error) {
env, _ = initEnv()
err = errors.New("initEnvirons failed")
return env, err
}
os.Args = []string{prog, "-convey-json"}
o := getOpts()
o.Init("blacklist", mflag.ContinueOnError)
o.SetOutput(act)
main()
So(act.String(), ShouldEqual, exp)
os.Args = origArgs
})
})
}
func TestScreenLog(t *testing.T) {
Convey("Testing ScreenLog()", t, func() {
haveTerm = func() bool {
return true
}
So(screenLog(""), ShouldNotBeNil)
})
}
func TestExitCmd(t *testing.T) {
Convey("Testing exitCmd", t, func() {
var act int
exitCmd = func(i int) {
act = i
}
exitCmd(0)
So(act, ShouldEqual, 0)
})
}
func TestInitEnv(t *testing.T) {
Convey("Testing initEnv", t, func() {
var err error
initEnv := func() (*e.Config, error) {
return &e.Config{
Env: &e.Env{Arch: "MegaOS"},
}, nil
}
act, _ := initEnv()
exp := "MegaOS"
So(act.Arch, ShouldEqual, exp)
origArgs := os.Args
o := getOpts()
o.setArgs()
origBkpCfgFile := bkpCfgFile
bkpCfgFile = "github.com/britannic/blacklist/internal/testdata/config.test.boot"
c := o.initEdgeOS()
*o.ARCH = *o.MIPS64
*o.Safe = true
c, err = loadConfig(c, o)
So(err, ShouldBeNil)
So(c, ShouldNotBeNil)
bkpCfgFile = origBkpCfgFile
os.Args = origArgs
})
}
func TestProcessObjects(t *testing.T) {
c, _ := initEnv()
badFileError := `open EinenSieAugenBlick/domains.tasty.blacklist.conf: no such file or directory`
Convey("Testing processObjects", t, func() {
Convey("Testing config is correctly loaded ", func() {
So(c.String(), ShouldEqual, mainGetConfig)
err := processObjects(c,
[]e.IFace{
e.ExRtObj,
e.ExDmObj,
e.ExHtObj,
})
So(err, ShouldBeNil)
})
Convey("Testing that c.Dex is correct after the load ", func() {
So(c.Dex.String(), ShouldEqual, expMap)
})
Convey("Testing that c.Exc is correct after the load ", func() {
So(c.Exc.String(), ShouldEqual, expMap)
})
Convey("Forcing processObjects to fail ", func() {
So(processObjects(c, []e.IFace{100}), ShouldNotBeNil)
})
Convey("Testing processObjects() with a non-existent directory ", func() {
c.Dir = "EinenSieAugenBlick"
So(
processObjects(c, []e.IFace{e.FileObj}),
ShouldResemble,
errors.New(badFileError),
)
})
})
}
func TestSetArgs(t *testing.T) {
var (
origArgs = os.Args
prog = path.Base(os.Args[0])
)
exitCmd = func(int) {}
defer func() { os.Args = origArgs }()
tests := []struct {
name string
args []string
exp interface{}
}{
{
name: "h",
args: []string{prog, "-convey-json", "-h"},
exp: true,
},
{
name: "debug",
args: []string{prog, "-debug"},
exp: true,
},
{
name: "dryrun",
args: []string{prog, "-dryrun"},
exp: true,
},
{
name: "version",
args: []string{prog, "-version"},
exp: true,
},
{
name: "v",
args: []string{prog, "-v"},
exp: true,
},
{
name: "invalid flag",
args: []string{prog, "-z"},
exp: readGolden(t, "testInvalidArgs"),
},
}
for _, tt := range tests {
os.Args = nil
if tt.args != nil {
os.Args = tt.args
}
env := getOpts()
env.Init(prog, mflag.ContinueOnError)
Convey("Testing commandline output", t, func() {
Convey("Testing setArgs() with "+tt.name+"\n", func() {
switch {
case tt.name == "invalid flag":
act := new(bytes.Buffer)
env.SetOutput(act)
env.setArgs()
// *update = true // uncomment to get latest golden file
writeGolden(t, act.Bytes(), "testInvalidArgs")
So(act.Bytes(), ShouldResemble, tt.exp.([]byte))
default:
env.setArgs()
So(fmt.Sprint(env.Lookup(tt.name).Value.String()), ShouldEqual, fmt.Sprint(tt.exp))
}
})
})
}
}
func TestBasename(t *testing.T) {
Convey("Testing basename()", t, func() {
tests := []struct {
s string
exp string
}{
{s: "e.txt", exp: "e"},
{s: "/internal/edgeos", exp: "edgeos"},
}
for _, tt := range tests {
So(basename(tt.s), ShouldEqual, tt.exp)
}
})
}
func TestBuild(t *testing.T) {
Convey("Testing Build() variables", t, func() {
want := map[string]string{
"build": build,
"githash": githash,
"version": version,
}
for k := range want {
So(want[k], ShouldEqual, "UNKNOWN")
}
})
}
func TestGetCFG(t *testing.T) {
Convey("Testing getCFG()", t, func() {
exitCmd = func(int) {}
o := getOpts()
c := o.initEdgeOS()
c.Blacklist(o.getCFG(c))
So(c.String(), ShouldEqual, mainGetConfig)
origBkpCfgFile := bkpCfgFile
bkpCfgFile = "github.com/britannic/blacklist/internal/testdata/config.test.boot"
c.Blacklist(o.getCFG(c))
So(c.String(), ShouldEqual, mainGetConfig)
bkpCfgFile = origBkpCfgFile
origFile := *o.File
*o.File = "github.com/britannic/blacklist/internal/testdata/config.test.boot"
c.Blacklist(o.getCFG(c))
So(c.String(), ShouldEqual, mainGetConfig)
*o.File = origFile
*o.MIPS64 = "arm64"
c = o.initEdgeOS()
c.Blacklist(o.getCFG(c))
So(c.String(), ShouldEqual, intelCfg)
// *o.MIPS64 = "arm64"
// c = o.initEdgeOS()
// c.Blacklist(o.getCFG(c))
// So(c.String(), ShouldEqual, intelCfg)
})
}
func TestFiles(t *testing.T) {
Convey("Testing files()", t, func() {
exp := ""
env, _ := initEnv()
act := files(env)
So(fmt.Sprintf("%v", act), ShouldEqual, fmt.Sprintf("%v", exp))
})
}
func TestReloadDNS(t *testing.T) {
Convey("Testing ReloadDNS()", t, func() {
var (
act string
exp = "[Successfully restarted dnsmasq]"
)
// if IsDrone() {
// exp = "ReloadDNS(): [dnsmasq: unrecognized service\n]\n"
// }
c, _ := initEnv()
exitCmd = func(int) {}
logPrintf = func(s string, v ...interface{}) {
act = fmt.Sprintf(s, v)
}
reloadDNS(c)
So(act, ShouldEqual, exp)
})
}
func TestRemoveStaleFiles(t *testing.T) {
Convey("Testing removeStaleFiles()", t, func() {
c, _ := initEnv()
So(removeStaleFiles(c), ShouldBeNil)
_ = c.SetOpt(e.Dir("EinenSieAugenBlick"), e.Ext("[]a]"), e.FileNameFmt("[]a]"), e.WCard(e.Wildcard{Node: "[]a]", Name: "]"}))
So(removeStaleFiles(c), ShouldNotBeNil)
})
}
func TestNewScreenLogBackend(t *testing.T) {
tests := []struct {
exp bool
colors []string
prefix string
}{
{exp: true, colors: boldcolors, prefix: "test"},
{exp: false, colors: []string{}, prefix: "test"},
}
Convey("Testing newScreenLogBackend()", t, func() {
for _, test := range tests {
act := newScreenLogBackend(test.colors, test.prefix)
So(act.Color, ShouldEqual, test.exp)
}
})
}
func TestSetArch(t *testing.T) {
Convey("Testing getCFG()", t, func() {
exitCmd = func(int) {}
o := getOpts()
tests := []struct {
arch string
exp string
}{
{arch: "mips64", exp: "/etc/dnsmasq.d"},
{arch: "linux", exp: "/tmp"},
{arch: "darwin", exp: "/tmp"},
}
for _, test := range tests {
So(o.setDir(test.arch), ShouldEqual, test.exp)
}
})
}
func TestSetLogFile(t *testing.T) {
oldprog := prog
prog = "update-dnsmasq"
tests := []struct {
os string
exp string
}{
{os: "darwin", exp: fmt.Sprintf("/tmp/%s.log", prog)},
{os: "linux", exp: fmt.Sprintf("/var/log/%s.log", prog)},
}
Convey("Testing setLogFile", t, func() {
for _, tt := range tests {
Convey("with OS: "+tt.os, func() {
So(setLogFile(tt.os), ShouldEqual, tt.exp)
})
}
})
prog = oldprog
}
func TestInitEdgeOS(t *testing.T) {
Convey("Testing initEdgeOS", t, func() {
exitCmd = func(int) {}
o := getOpts()
p := o.initEdgeOS()
exp := `{
"Log": {
"Module": "blacklist",
"ExtraCalldepth": 0
},
"API": "/bin/cli-shell-api",
"Arch": "arm64",
"Bash": "/bin/bash",
"Cores": 2,
"Disabled": false,
"Dex": {},
"Dir": "/tmp",
"dnsmasq service": "/etc/init.d/dnsmasq restart",
"Exc": {},
"dnsmasq fileExt.": "blacklist.conf",
"File name fmt": "%v/%v.%v.%v",
"HTTP method": "GET",
"Prefix": {},
"Timeout": 30000000000,
"Wildcard": {
"Node": "*s",
"Name": "*"
}
}`
So(fmt.Sprint(p.Env), ShouldEqual, exp)
})
}
var (
mainGetConfig = `{
"nodes": [{
"blacklist": {
"disabled": "false",
"ip": "192.168.168.1",
"excludes": [
"1e100.net",
"2o7.net",
"adobedtm.com",
"akamai.net",
"akamaihd.net",
"amazon.com",
"amazonaws.com",
"apple.com",
"ask.com",
"avast.com",
"avira-update.com",
"bannerbank.com",
"bing.com",
"bit.ly",
"bitdefender.com",
"cdn.ravenjs.com",
"cdn.visiblemeasures.com",
"cloudfront.net",
"coremetrics.com",
"dropbox.com",
"ebay.com",
"edgesuite.net",
"evernote.com",
"express.co.uk",
"feedly.com",
"freedns.afraid.org",
"github.com",
"githubusercontent.com",
"global.ssl.fastly.net",
"google.com",
"googleads.g.doubleclick.net",
"googleadservices.com",
"googleapis.com",
"googletagmanager.com",
"googleusercontent.com",
"gstatic.com",
"gvt1.com",
"gvt1.net",
"hb.disney.go.com",
"herokuapp.com",
"hp.com",
"hulu.com",
"images-amazon.com",
"live.com",
"magnetmail1.net",
"microsoft.com",
"microsoftonline.com",
"msdn.com",
"msecnd.net",
"msftncsi.com",
"mywot.com",
"nsatc.net",
"paypal.com",
"pop.h-cdn.co",
"rackcdn.com",
"rarlab.com",
"schema.org",
"shopify.com",
"skype.com",
"smacargo.com",
"sourceforge.net",
"spotify.com",
"spotify.edgekey.net",
"spotilocal.com",
"ssl-on9.com",
"ssl-on9.net",
"sstatic.net",
"static.chartbeat.com",
"storage.googleapis.com",
"twimg.com",
"viewpoint.com",
"windows.net",
"xboxlive.com",
"yimg.com",
"ytimg.com"
],
"includes": [
"adk2x.com",
"adsrvr.org",
"adtechus.net",
"advertising.com",
"centade.com",
"doubleclick.net",
"fastplayz.com",
"free-counter.co.uk",
"hilltopads.net",
"intellitxt.com",
"kiosked.com",
"patoghee.in",
"themillionaireinpjs.com",
"traktrafficflow.com",
"wwwpromoter.com"
],
"sources": [{}]
},
"domains": {
"disabled": "false",
"excludes": [],
"includes": [],
"sources": [{
"NoBitCoin": {
"disabled": "false",
"description": "Blocking Web Browser Bitcoin Mining",
"prefix": "0.0.0.0",
"url": "https://raw.githubusercontent.com/hoshsadiq/adblock-nocoin-list/master/hosts.txt",
},
"malc0de": {
"disabled": "false",
"description": "List of zones serving malicious executables observed by malc0de.com/database/",
"prefix": "zone",
"url": "http://malc0de.com/bl/ZONES",
},
"malwaredomains.com": {
"disabled": "false",
"description": "Just Domains",
"url": "http://mirror1.malwaredomains.com/files/justdomains",
},
"simple_tracking": {
"disabled": "false",
"description": "Basic tracking list by Disconnect",
"url": "https://s3.amazonaws.com/lists.disconnect.me/simple_tracking.txt",
},
"zeus": {
"disabled": "false",
"description": "abuse.ch ZeuS domain blocklist",
"url": "https://zeustracker.abuse.ch/blocklist.php?download=domainblocklist",
},
"tasty": {
"disabled": "false",
"description": "File source",
"ip": "10.10.10.10",
"file": "./internal/testdata/blist.hosts.src",
}
}]
},
"hosts": {
"disabled": "false",
"excludes": [],
"includes": [
"ads.feedly.com",
"beap.gemini.yahoo.com"
],
"sources": [{
"githubSteveBlack": {
"disabled": "false",
"description": "Blacklists adware and malware websites",
"prefix": "0.0.0.0",
"url": "https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts",
},
"hostsfile.org": {
"disabled": "false",
"description": "hostsfile.org bad hosts blacklist",
"prefix": "127.0.0.1",
"url": "http://www.hostsfile.org/Downloads/hosts.txt",
},
"openphish": {
"disabled": "false",
"description": "OpenPhish automatic phishing detection",
"prefix": "http",
"url": "https://openphish.com/feed.txt",
},
"sysctl.org": {
"disabled": "false",
"description": "This hosts file is a merged collection of hosts from Cameleon",
"prefix": "127.0.0.1",
"url": "http://sysctl.org/cameleon/hosts",
}
}]
}
}]
}`
expMap = `"1e100.net":{},
"2o7.net":{},
"adobedtm.com":{},
"akamai.net":{},
"akamaihd.net":{},
"amazon.com":{},
"amazonaws.com":{},
"apple.com":{},
"ask.com":{},
"avast.com":{},
"avira-update.com":{},
"bannerbank.com":{},
"bing.com":{},
"bit.ly":{},
"bitdefender.com":{},
"cdn.ravenjs.com":{},
"cdn.visiblemeasures.com":{},
"cloudfront.net":{},
"coremetrics.com":{},
"dropbox.com":{},
"ebay.com":{},
"edgesuite.net":{},
"evernote.com":{},
"express.co.uk":{},
"feedly.com":{},
"freedns.afraid.org":{},
"github.com":{},
"githubusercontent.com":{},
"global.ssl.fastly.net":{},
"google.com":{},
"googleads.g.doubleclick.net":{},
"googleadservices.com":{},
"googleapis.com":{},
"googletagmanager.com":{},
"googleusercontent.com":{},
"gstatic.com":{},
"gvt1.com":{},
"gvt1.net":{},
"hb.disney.go.com":{},
"herokuapp.com":{},
"hp.com":{},
"hulu.com":{},
"images-amazon.com":{},
"live.com":{},
"magnetmail1.net":{},
"microsoft.com":{},
"microsoftonline.com":{},
"msdn.com":{},
"msecnd.net":{},
"msftncsi.com":{},
"mywot.com":{},
"nsatc.net":{},
"paypal.com":{},
"pop.h-cdn.co":{},
"rackcdn.com":{},
"rarlab.com":{},
"schema.org":{},
"shopify.com":{},
"skype.com":{},
"smacargo.com":{},
"sourceforge.net":{},
"spotify.com":{},
"spotify.edgekey.net":{},
"spotilocal.com":{},
"ssl-on9.com":{},
"ssl-on9.net":{},
"sstatic.net":{},
"static.chartbeat.com":{},
"storage.googleapis.com":{},
"twimg.com":{},
"viewpoint.com":{},
"windows.net":{},
"xboxlive.com":{},
"yimg.com":{},
"ytimg.com":{},
`
intelCfg = `{
"nodes": [{
}]
}`
)