-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexamples_test.go
More file actions
1051 lines (908 loc) · 28.5 KB
/
examples_test.go
File metadata and controls
1051 lines (908 loc) · 28.5 KB
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
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package granular_test
import (
"fmt"
"log"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/davecgh/go-spew/spew"
"github.com/gophersatwork/granular"
"github.com/spf13/afero"
)
func TestArtifactCache(t *testing.T) {
isDebug := false // Set to true when you want to troubleshoot issues visually.
memFs := afero.NewMemMapFs()
cacheRoot := ".artifact-cache"
cache, err := granular.New(cacheRoot, granular.WithFs(memFs))
if err != nil {
log.Fatalf("Failed to create cache: %v", err)
}
schemaFile := "schema.proto"
err = afero.WriteFile(memFs, schemaFile, []byte("fake schema.proto content"), 0o644)
if err != nil {
log.Fatalf("Failed to write schema file: %v", err)
}
key := granular.Key{
Inputs: []granular.Input{
granular.FileInput{
Path: schemaFile,
Fs: memFs,
},
},
Extra: map[string]string{
"generator_version": "2.0.1",
"language": "go",
},
}
if isDebug {
spew.Dump(key)
}
// "Generate" the artifact
var outputFile string
if outputFile, err = generateArtifact(memFs, schemaFile); err != nil {
log.Fatalf("Generation failed: %v", err)
}
// Store the artifact in cache
result := granular.Result{
Path: outputFile,
Metadata: map[string]string{
"generation_time": fixedNowFunc().Format(time.RFC3339), // fixedNowFunc to keep the test results deterministic
},
}
if isDebug {
spew.Dump(result)
}
if err := cache.Store(key, result); err != nil {
log.Printf("Warning: Failed to cache generated artifact: %v", err)
}
if isDebug {
printDirTree(memFs, cacheRoot)
}
res, found, err := cache.Get(key)
if err != nil || !found {
log.Fatalf("Failed to fetch artifact: %v", err)
}
if isDebug {
spew.Dump(res)
}
expectedResultPath := ".artifact-cache/objects/68/6832ec325639264c/output.go"
if res.Path != expectedResultPath {
log.Fatalf("Unexpected artifact output file. Expected %q, but found %q", expectedResultPath, res.Path)
}
expectedGenerationTime := fixedNowFunc().Format(time.RFC3339)
gotGenerationTime := res.Metadata["generation_time"]
if gotGenerationTime != expectedGenerationTime {
log.Fatalf("Unexpected generation time metadata. Expected %q, but found %q", expectedGenerationTime, gotGenerationTime)
}
}
func TestContentBasedFileCache(t *testing.T) {
isDebug := false // Set to true when you want to troubleshoot issues visually.
memFs := afero.NewMemMapFs()
cacheDir := ".file-cache"
cache, err := granular.New(cacheDir, granular.WithFs(memFs))
if err != nil {
t.Fatalf("Failed to create cache: %v", err)
}
// Create test file
filePath := "large-dataset.csv"
fileContent := "id,name,value\n1,item1,100\n2,item2,200\n3,item3,300\n"
err = afero.WriteFile(memFs, filePath, []byte(fileContent), 0o644)
if err != nil {
t.Fatalf("Failed to write test file: %v", err)
}
// Create a key based solely on the file content
key := granular.Key{
Inputs: []granular.Input{
granular.FileInput{Path: filePath, Fs: memFs},
},
}
if isDebug {
spew.Dump(key)
}
// First get should be a miss
processedFilePath := filePath + ".processed"
_, hit, err := cache.Get(key)
if err != nil {
t.Fatalf("Failed to get from cache: %v", err)
}
if hit {
t.Fatalf("Expected cache miss, but got a hit")
}
// Process the file (just create a mock processed file)
processedContent := "processed:" + fileContent
err = afero.WriteFile(memFs, processedFilePath, []byte(processedContent), 0o644)
if err != nil {
t.Fatalf("Failed to write processed file: %v", err)
}
// Store the processed file in cache
processResult := granular.Result{
Path: processedFilePath,
}
if isDebug {
spew.Dump(processResult)
}
if err := cache.Store(key, processResult); err != nil {
t.Fatalf("Failed to store in cache: %v", err)
}
if isDebug {
printDirTree(memFs, cacheDir)
}
// Second get should be a hit
result, hit, err := cache.Get(key)
if err != nil {
t.Fatalf("Failed to get from cache: %v", err)
}
if !hit {
t.Fatalf("Expected cache hit, but got a miss")
}
// Verify the cached file exists
cachedContent, err := afero.ReadFile(memFs, result.Path)
if err != nil {
t.Fatalf("Failed to read cached file: %v", err)
}
if string(cachedContent) != processedContent {
t.Fatalf("Cached content doesn't match. Expected %q, got %q", processedContent, string(cachedContent))
}
// Modify the original file
newFileContent := "id,name,value\n1,item1,100\n2,item2,200\n3,item3,300\n4,item4,400\n"
err = afero.WriteFile(memFs, filePath, []byte(newFileContent), 0o644)
if err != nil {
t.Fatalf("Failed to update test file: %v", err)
}
// Third get should be a miss due to modified content
_, hit, err = cache.Get(key)
if err != nil {
t.Fatalf("Failed to get from cache: %v", err)
}
if hit {
t.Fatalf("Expected cache miss after file modification, but got a hit")
}
}
func TestIncrementalComputation(t *testing.T) {
isDebug := false // Set to true when you want to troubleshoot issues visually.
memFs := afero.NewMemMapFs()
cacheDir := ".computation-cache"
cache, err := granular.New(cacheDir, granular.WithFs(memFs))
if err != nil {
t.Fatalf("Failed to create cache: %v", err)
}
// Create test directory and files
inputDir := "data"
err = memFs.MkdirAll(inputDir, 0o755)
if err != nil {
t.Fatalf("Failed to create input directory: %v", err)
}
// Create some data files
dataFiles := []struct {
name string
content string
}{
{"data1.txt", "This is data file 1"},
{"data2.txt", "This is data file 2"},
{"data3.txt", "This is data file 3"},
{"temp.tmp", "This is a temporary file that should be excluded"},
{"debug.log", "This is a log file that should be excluded"},
}
for _, df := range dataFiles {
filePath := filepath.Join(inputDir, df.name)
err = afero.WriteFile(memFs, filePath, []byte(df.content), 0o644)
if err != nil {
t.Fatalf("Failed to write data file %s: %v", df.name, err)
}
}
// Create config file
configFile := "config.json"
configContent := `{"parameter1": "value1", "parameter2": "value2"}`
err = afero.WriteFile(memFs, configFile, []byte(configContent), 0o644)
if err != nil {
t.Fatalf("Failed to write config file: %v", err)
}
// Create a key based on all input files and configuration
key := granular.Key{
Inputs: []granular.Input{
granular.DirectoryInput{
Path: inputDir,
Exclude: []string{"*.tmp", "*.log"},
Fs: memFs,
},
granular.FileInput{Path: configFile, Fs: memFs},
},
Extra: map[string]string{
"computation_version": "1.2.3",
},
}
if isDebug {
spew.Dump(key)
}
// First get should be a miss
outputFile := "results.json"
_, hit, err := cache.Get(key)
if err != nil {
t.Fatalf("Failed to get from cache: %v", err)
}
if hit {
t.Fatalf("Expected cache miss, but got a hit")
}
// Perform the computation (just create a mock result file)
resultContent := `{"result": "computed data", "count": 3}`
err = afero.WriteFile(memFs, outputFile, []byte(resultContent), 0o644)
if err != nil {
t.Fatalf("Failed to write result file: %v", err)
}
// Store the result in cache
computationResult := granular.Result{
Path: outputFile,
Metadata: map[string]string{
"completion_time": fixedNowFunc().Format(time.RFC3339),
"input_count": "3", // Excluding .tmp and .log files
},
}
if isDebug {
spew.Dump(computationResult)
}
if err := cache.Store(key, computationResult); err != nil {
t.Fatalf("Failed to store in cache: %v", err)
}
if isDebug {
printDirTree(memFs, cacheDir)
}
// Second get should be a hit
result, hit, err := cache.Get(key)
if err != nil {
t.Fatalf("Failed to get from cache: %v", err)
}
if !hit {
t.Fatalf("Expected cache hit, but got a miss")
}
// Verify the cached metadata
expectedCompletionTime := fixedNowFunc().Format(time.RFC3339)
gotCompletionTime := result.Metadata["completion_time"]
if gotCompletionTime != expectedCompletionTime {
t.Fatalf("Unexpected completion time metadata. Expected %q, but got %q", expectedCompletionTime, gotCompletionTime)
}
expectedInputCount := "3"
gotInputCount := result.Metadata["input_count"]
if gotInputCount != expectedInputCount {
t.Fatalf("Unexpected input count metadata. Expected %q, but got %q", expectedInputCount, gotInputCount)
}
// Modify one of the input files
modifiedDataPath := filepath.Join(inputDir, "data1.txt")
modifiedContent := "This is modified data file 1"
err = afero.WriteFile(memFs, modifiedDataPath, []byte(modifiedContent), 0o644)
if err != nil {
t.Fatalf("Failed to update data file: %v", err)
}
// Third get should be a miss due to modified input
_, hit, err = cache.Get(key)
if err != nil {
t.Fatalf("Failed to get from cache: %v", err)
}
if hit {
t.Fatalf("Expected cache miss after input modification, but got a hit")
}
}
func TestLocalDevOptimization(t *testing.T) {
isDebug := false // Set to true when you want to troubleshoot issues visually.
memFs := afero.NewMemMapFs()
cacheDir := ".dev-cache"
cache, err := granular.New(cacheDir, granular.WithFs(memFs))
if err != nil {
t.Fatalf("Failed to create cache: %v", err)
}
// Create test directory structure
srcDir := "src"
err = memFs.MkdirAll(srcDir, 0o755)
if err != nil {
t.Fatalf("Failed to create src directory: %v", err)
}
// Create nested directories
nestedDirs := []string{
filepath.Join(srcDir, "api"),
filepath.Join(srcDir, "models"),
filepath.Join(srcDir, "utils"),
}
for _, dir := range nestedDirs {
err = memFs.MkdirAll(dir, 0o755)
if err != nil {
t.Fatalf("Failed to create directory %s: %v", dir, err)
}
}
// Create some source files
sourceFiles := []struct {
path string
content string
}{
{filepath.Join(srcDir, "api", "handlers.go"), "package api\n\nfunc Handler() {}\n"},
{filepath.Join(srcDir, "models", "user.go"), "package models\n\ntype User struct {}\n"},
{filepath.Join(srcDir, "utils", "helpers.go"), "package utils\n\nfunc Helper() {}\n"},
}
for _, sf := range sourceFiles {
err = afero.WriteFile(memFs, sf.path, []byte(sf.content), 0o644)
if err != nil {
t.Fatalf("Failed to write source file %s: %v", sf.path, err)
}
}
// Create config directory and files
configDir := "config"
err = memFs.MkdirAll(configDir, 0o755)
if err != nil {
t.Fatalf("Failed to create config directory: %v", err)
}
configFiles := []struct {
path string
content string
}{
{filepath.Join(configDir, "app.yaml"), "environment: development\n"},
{filepath.Join(configDir, "database.yaml"), "driver: sqlite\n"},
}
for _, cf := range configFiles {
err = afero.WriteFile(memFs, cf.path, []byte(cf.content), 0o644)
if err != nil {
t.Fatalf("Failed to write config file %s: %v", cf.path, err)
}
}
// Create dependency files
err = afero.WriteFile(memFs, "go.mod", []byte("module example.com/myapp\n\ngo 1.16\n"), 0o644)
if err != nil {
t.Fatalf("Failed to write go.mod file: %v", err)
}
err = afero.WriteFile(memFs, "go.sum", []byte("example.com/dependency v1.0.0 h1:hash\n"), 0o644)
if err != nil {
t.Fatalf("Failed to write go.sum file: %v", err)
}
// Define inputs for the development task
key := granular.Key{
Inputs: []granular.Input{
// Track all source files
granular.GlobInput{Pattern: filepath.Join(srcDir, "**", "*.go"), Fs: memFs},
// Track configuration files
granular.GlobInput{Pattern: filepath.Join(configDir, "*.yaml"), Fs: memFs},
// Track dependencies
granular.FileInput{Path: "go.mod", Fs: memFs},
granular.FileInput{Path: "go.sum", Fs: memFs},
},
Extra: map[string]string{
"task": "lint",
},
}
if isDebug {
spew.Dump(key)
}
// First get should be a miss
_, hit, err := cache.Get(key)
if err != nil {
t.Fatalf("Failed to get from cache: %v", err)
}
if hit {
t.Fatalf("Expected cache miss, but got a hit")
}
// Run the linter (simulate by creating an output file)
lintOutputFile := "lint-output.txt"
lintOutput := "src/api/handlers.go:3:1: exported function Handler should have comment\n"
err = afero.WriteFile(memFs, lintOutputFile, []byte(lintOutput), 0o644)
if err != nil {
t.Fatalf("Failed to write lint output file: %v", err)
}
// Store the result in cache
lintResult := granular.Result{
Path: lintOutputFile,
Metadata: map[string]string{
"lint_status": "fail",
"exit_code": "1",
},
}
if isDebug {
spew.Dump(lintResult)
}
if err := cache.Store(key, lintResult); err != nil {
t.Fatalf("Failed to store in cache: %v", err)
}
if isDebug {
printDirTree(memFs, cacheDir)
}
// Second get should be a hit
result, hit, err := cache.Get(key)
if err != nil {
t.Fatalf("Failed to get from cache: %v", err)
}
if !hit {
t.Fatalf("Expected cache hit, but got a miss")
}
// Verify the cached metadata
expectedLintStatus := "fail"
gotLintStatus := result.Metadata["lint_status"]
if gotLintStatus != expectedLintStatus {
t.Fatalf("Unexpected lint status metadata. Expected %q, but got %q", expectedLintStatus, gotLintStatus)
}
expectedExitCode := "1"
gotExitCode := result.Metadata["exit_code"]
if gotExitCode != expectedExitCode {
t.Fatalf("Unexpected exit code metadata. Expected %q, but got %q", expectedExitCode, gotExitCode)
}
// Verify the cached file content
cachedContent, err := afero.ReadFile(memFs, result.Path)
if err != nil {
t.Fatalf("Failed to read cached file: %v", err)
}
if string(cachedContent) != lintOutput {
t.Fatalf("Cached content doesn't match. Expected %q, got %q", lintOutput, string(cachedContent))
}
// Fix the lint issue
fixedHandlerContent := "package api\n\n// Handler is an API handler\nfunc Handler() {}\n"
err = afero.WriteFile(memFs, filepath.Join(srcDir, "api", "handlers.go"), []byte(fixedHandlerContent), 0o644)
if err != nil {
t.Fatalf("Failed to update source file: %v", err)
}
// Third get should be a miss due to modified source
_, hit, err = cache.Get(key)
if err != nil {
t.Fatalf("Failed to get from cache: %v", err)
}
if hit {
t.Fatalf("Expected cache miss after source modification, but got a hit")
}
}
func TestCIOptimization(t *testing.T) {
isDebug := false // Set to true when you want to troubleshoot issues visually.
memFs := afero.NewMemMapFs()
cacheDir := ".ci-cache"
cache, err := granular.New(cacheDir, granular.WithFs(memFs))
if err != nil {
t.Fatalf("Failed to create cache: %v", err)
}
// Create test directory structure
err = memFs.MkdirAll(".github/workflows", 0o755)
if err != nil {
t.Fatalf("Failed to create .github/workflows directory: %v", err)
}
// Create CI configuration
ciConfig := `name: CI
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-go@v2
with:
go-version: 1.16
- run: go test ./...
`
err = afero.WriteFile(memFs, ".github/workflows/ci.yml", []byte(ciConfig), 0o644)
if err != nil {
t.Fatalf("Failed to write CI config file: %v", err)
}
// Create source and test files
sourceFiles := []struct {
path string
content string
}{
{"main.go", "package main\n\nfunc main() {}\n"},
{"utils.go", "package main\n\nfunc util() string { return \"util\" }\n"},
{"main_test.go", "package main\n\nimport \"testing\"\n\nfunc TestMain(t *testing.T) { t.Log(\"test passed\") }\n"},
{"utils_test.go", "package main\n\nimport \"testing\"\n\nfunc TestUtil(t *testing.T) { t.Log(\"test passed\") }\n"},
}
for _, sf := range sourceFiles {
err = afero.WriteFile(memFs, sf.path, []byte(sf.content), 0o644)
if err != nil {
t.Fatalf("Failed to write file %s: %v", sf.path, err)
}
}
// Create dependency files
err = afero.WriteFile(memFs, "go.mod", []byte("module example.com/citest\n\ngo 1.16\n"), 0o644)
if err != nil {
t.Fatalf("Failed to write go.mod file: %v", err)
}
err = afero.WriteFile(memFs, "go.sum", []byte("example.com/dependency v1.0.0 h1:hash\n"), 0o644)
if err != nil {
t.Fatalf("Failed to write go.sum file: %v", err)
}
// Define inputs for the CI task
key := granular.Key{
Inputs: []granular.Input{
// Track all source and test files
granular.GlobInput{Pattern: "**/*.go", Fs: memFs},
// Track configuration files
granular.FileInput{Path: ".github/workflows/ci.yml", Fs: memFs},
granular.FileInput{Path: "go.mod", Fs: memFs},
granular.FileInput{Path: "go.sum", Fs: memFs},
},
Extra: map[string]string{
"go_version": "1.16",
"os": "linux",
"task": "test",
},
}
if isDebug {
spew.Dump(key)
}
// First get should be a miss
_, hit, err := cache.Get(key)
if err != nil {
t.Fatalf("Failed to get from cache: %v", err)
}
if hit {
t.Fatalf("Expected cache miss, but got a hit")
}
// Run the tests (simulate by creating an output file)
testOutputFile := "test-output.txt"
testOutput := "=== RUN TestMain\n--- PASS: TestMain (0.00s)\n=== RUN TestUtil\n--- PASS: TestUtil (0.00s)\nPASS\n"
err = afero.WriteFile(memFs, testOutputFile, []byte(testOutput), 0o644)
if err != nil {
t.Fatalf("Failed to write test output file: %v", err)
}
// Store the result in cache
testResult := granular.Result{
Path: testOutputFile,
Metadata: map[string]string{
"test_status": "pass",
"exit_code": "0",
"test_count": "2",
},
}
if isDebug {
spew.Dump(testResult)
}
if err := cache.Store(key, testResult); err != nil {
t.Fatalf("Failed to store in cache: %v", err)
}
if isDebug {
printDirTree(memFs, cacheDir)
}
// Second get should be a hit
result, hit, err := cache.Get(key)
if err != nil {
t.Fatalf("Failed to get from cache: %v", err)
}
if !hit {
t.Fatalf("Expected cache hit, but got a miss")
}
// Verify the cached metadata
expectedTestStatus := "pass"
gotTestStatus := result.Metadata["test_status"]
if gotTestStatus != expectedTestStatus {
t.Fatalf("Unexpected test status metadata. Expected %q, but got %q", expectedTestStatus, gotTestStatus)
}
expectedTestCount := "2"
gotTestCount := result.Metadata["test_count"]
if gotTestCount != expectedTestCount {
t.Fatalf("Unexpected test count metadata. Expected %q, but got %q", expectedTestCount, gotTestCount)
}
// Verify the cached file content
cachedContent, err := afero.ReadFile(memFs, result.Path)
if err != nil {
t.Fatalf("Failed to read cached file: %v", err)
}
if string(cachedContent) != testOutput {
t.Fatalf("Cached content doesn't match. Expected %q, got %q", testOutput, string(cachedContent))
}
// Add a new test
newTestFile := "new_test.go"
newTestContent := "package main\n\nimport \"testing\"\n\nfunc TestNew(t *testing.T) { t.Log(\"new test passed\") }\n"
err = afero.WriteFile(memFs, newTestFile, []byte(newTestContent), 0o644)
if err != nil {
t.Fatalf("Failed to write new test file: %v", err)
}
// Third get should be a miss due to the new test file
_, hit, err = cache.Get(key)
if err != nil {
t.Fatalf("Failed to get from cache: %v", err)
}
if hit {
t.Fatalf("Expected cache miss after adding new test, but got a hit")
}
}
func TestDataPipeline(t *testing.T) {
isDebug := false // Set to true when you want to troubleshoot issues visually.
memFs := afero.NewMemMapFs()
cacheDir := ".pipeline-cache"
cache, err := granular.New(cacheDir, granular.WithFs(memFs))
if err != nil {
t.Fatalf("Failed to create cache: %v", err)
}
// Create raw data file
rawDataFile := "raw-data.csv"
rawDataContent := "id,name,value\n1,item1,100\n2,item2,200\n3,item3,300\n"
err = afero.WriteFile(memFs, rawDataFile, []byte(rawDataContent), 0o644)
if err != nil {
t.Fatalf("Failed to write raw data file: %v", err)
}
// Create config directory and files
configDir := "config"
err = memFs.MkdirAll(configDir, 0o755)
if err != nil {
t.Fatalf("Failed to create config directory: %v", err)
}
configFiles := []struct {
name string
content string
}{
{"extract.yaml", "source: csv\nformat: json\n"},
{"transform.yaml", "operations: [normalize, validate]\n"},
{"load.yaml", "destination: database\nformat: json\n"},
}
for _, cf := range configFiles {
filePath := filepath.Join(configDir, cf.name)
err = afero.WriteFile(memFs, filePath, []byte(cf.content), 0o644)
if err != nil {
t.Fatalf("Failed to write config file %s: %v", cf.name, err)
}
}
// Define pipeline stages
stages := []struct {
name string
input string
output string
content string
}{
{
name: "extract",
input: rawDataFile,
output: "extracted-data.json",
content: `{"extracted": [{"id": 1, "name": "item1", "value": 100}, {"id": 2, "name": "item2", "value": 200}, {"id": 3, "name": "item3", "value": 300}]}`,
},
{
name: "transform",
input: "extracted-data.json",
output: "transformed-data.json",
content: `{"transformed": [{"id": 1, "name": "item1", "value": 100}, {"id": 2, "name": "item2", "value": 200}, {"id": 3, "name": "item3", "value": 300}]}`,
},
{
name: "load",
input: "transformed-data.json",
output: "final-output.json",
content: `{"loaded": true, "count": 3, "status": "success"}`,
},
}
// Process each stage
for i, stage := range stages {
// Create a key for this stage
var inputs []granular.Input
// If this is the first stage, use the raw input file
if i == 0 {
inputs = []granular.Input{
granular.FileInput{Path: stage.input, Fs: memFs},
}
} else {
// Otherwise, use the output from the previous stage
inputs = []granular.Input{
granular.FileInput{Path: stages[i-1].output, Fs: memFs},
}
}
// Add configuration file
configFile := filepath.Join(configDir, stage.name+".yaml")
inputs = append(inputs, granular.FileInput{Path: configFile, Fs: memFs})
key := granular.Key{
Inputs: inputs,
Extra: map[string]string{
"stage": stage.name,
"version": "1.0.0",
},
}
if isDebug {
spew.Dump(key)
}
// First get should be a miss
_, hit, err := cache.Get(key)
if err != nil {
t.Fatalf("Failed to get from cache for stage %s: %v", stage.name, err)
}
if hit {
t.Fatalf("Expected cache miss for stage %s, but got a hit", stage.name)
}
// Process this stage (create the output file)
err = afero.WriteFile(memFs, stage.output, []byte(stage.content), 0o644)
if err != nil {
t.Fatalf("Failed to write output file for stage %s: %v", stage.name, err)
}
// Store the result in cache
stageResult := granular.Result{
Path: stage.output,
Metadata: map[string]string{
"stage": stage.name,
"process_time": fixedNowFunc().Format(time.RFC3339),
},
}
if isDebug {
spew.Dump(stageResult)
}
if err := cache.Store(key, stageResult); err != nil {
t.Fatalf("Failed to store in cache for stage %s: %v", stage.name, err)
}
if isDebug {
printDirTree(memFs, cacheDir)
}
// Second get should be a hit
result, hit, err := cache.Get(key)
if err != nil {
t.Fatalf("Failed to get from cache for stage %s: %v", stage.name, err)
}
if !hit {
t.Fatalf("Expected cache hit for stage %s, but got a miss", stage.name)
}
// Verify the cached metadata
expectedStage := stage.name
gotStage := result.Metadata["stage"]
if gotStage != expectedStage {
t.Fatalf("Unexpected stage metadata. Expected %q, but got %q", expectedStage, gotStage)
}
expectedProcessTime := fixedNowFunc().Format(time.RFC3339)
gotProcessTime := result.Metadata["process_time"]
if gotProcessTime != expectedProcessTime {
t.Fatalf("Unexpected process time metadata. Expected %q, but got %q", expectedProcessTime, gotProcessTime)
}
// Verify the cached file content
cachedContent, err := afero.ReadFile(memFs, result.Path)
if err != nil {
t.Fatalf("Failed to read cached file for stage %s: %v", stage.name, err)
}
if string(cachedContent) != stage.content {
t.Fatalf("Cached content doesn't match for stage %s. Expected %q, got %q", stage.name, stage.content, string(cachedContent))
}
}
// Modify the raw data file
newRawDataContent := "id,name,value\n1,item1,100\n2,item2,200\n3,item3,300\n4,item4,400\n"
err = afero.WriteFile(memFs, rawDataFile, []byte(newRawDataContent), 0o644)
if err != nil {
t.Fatalf("Failed to update raw data file: %v", err)
}
// First stage should be a miss due to modified input
firstStage := stages[0]
firstStageKey := granular.Key{
Inputs: []granular.Input{
granular.FileInput{Path: firstStage.input, Fs: memFs},
granular.FileInput{Path: filepath.Join(configDir, firstStage.name+".yaml"), Fs: memFs},
},
Extra: map[string]string{
"stage": firstStage.name,
"version": "1.0.0",
},
}
_, firstStageHit, firstStageErr := cache.Get(firstStageKey)
if firstStageErr != nil {
t.Fatalf("Failed to get from cache for first stage after modification: %v", firstStageErr)
}
if firstStageHit {
t.Fatalf("Expected cache miss for first stage after input modification, but got a hit")
}
}
func TestBuildSystemCache(t *testing.T) {
isDebug := false // Set to true when you want to troubleshoot issues visually.
memFs := afero.NewMemMapFs()
cacheDir := ".build-cache"
cache, err := granular.New(cacheDir, granular.WithFs(memFs))
if err != nil {
t.Fatalf("Failed to create cache: %v", err)
}
// Create test files
goModContent := "module example.com/myapp\n\ngo 1.16\n"
goSumContent := "example.com/dependency v1.0.0 h1:hash\n"
mainGoContent := "package main\n\nfunc main() {\n\tfmt.Println(\"Hello, world!\")\n}\n"
err = afero.WriteFile(memFs, "go.mod", []byte(goModContent), 0o644)
if err != nil {
t.Fatalf("Failed to write go.mod file: %v", err)
}
err = afero.WriteFile(memFs, "go.sum", []byte(goSumContent), 0o644)
if err != nil {
t.Fatalf("Failed to write go.sum file: %v", err)
}
err = afero.WriteFile(memFs, "main.go", []byte(mainGoContent), 0o644)
if err != nil {
t.Fatalf("Failed to write main.go file: %v", err)
}
// Define cache key based on source files
key := granular.Key{
Inputs: []granular.Input{
// Track all source files
granular.GlobInput{Pattern: "*.go", Fs: memFs},
// Track build configuration
granular.FileInput{Path: "go.mod", Fs: memFs},
granular.FileInput{Path: "go.sum", Fs: memFs},
},
Extra: map[string]string{
"go_version": "1.16",
"os": "linux",
"arch": "amd64",
},
}
if isDebug {
spew.Dump(key)
}
// First get should be a miss
_, hit, err := cache.Get(key)
if err != nil {
t.Fatalf("Failed to get from cache: %v", err)
}
if hit {
t.Fatalf("Expected cache miss, but got a hit")
}
// "Build" the application
binaryContent := []byte("mock binary content")
binaryPath := "myapp"
err = afero.WriteFile(memFs, binaryPath, binaryContent, 0o755)
if err != nil {
t.Fatalf("Failed to write binary file: %v", err)
}
// Store the build artifact in cache
buildResult := granular.Result{
Path: binaryPath,
Metadata: map[string]string{
"build_time": fixedNowFunc().Format(time.RFC3339),
},
}
if isDebug {
spew.Dump(buildResult)
}
if err := cache.Store(key, buildResult); err != nil {
t.Fatalf("Failed to store in cache: %v", err)
}
if isDebug {
printDirTree(memFs, cacheDir)
}
// Second get should be a hit
result, hit, err := cache.Get(key)
if err != nil {
t.Fatalf("Failed to get from cache: %v", err)
}
if !hit {
t.Fatalf("Expected cache hit, but got a miss")
}
// Verify the cached data
expectedBuildTime := fixedNowFunc().Format(time.RFC3339)
gotBuildTime := result.Metadata["build_time"]
if gotBuildTime != expectedBuildTime {
t.Fatalf("Unexpected build time metadata. Expected %q, but got %q", expectedBuildTime, gotBuildTime)
}
// Modify a source file
newMainGoContent := "package main\n\nfunc main() {\n\tfmt.Println(\"Hello, updated world!\")\n}\n"
err = afero.WriteFile(memFs, "main.go", []byte(newMainGoContent), 0o644)
if err != nil {
t.Fatalf("Failed to update main.go file: %v", err)
}
// Third get should be a miss due to modified source
_, hit, err = cache.Get(key)