-
Notifications
You must be signed in to change notification settings - Fork 0
/
phredsort_test.go
1070 lines (997 loc) · 27.1 KB
/
phredsort_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
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 main
import (
"fmt"
"io"
"math"
"os"
"path/filepath"
"reflect"
"sort"
"strings"
"testing"
"github.com/shenwei356/bio/seq"
"github.com/shenwei356/bio/seqio/fastx"
"github.com/shenwei356/xopen"
)
// Helper function to create test FASTX records
func createTestRecord(name string, sequence string, quality string) *fastx.Record {
return &fastx.Record{
Name: []byte(name),
Seq: &seq.Seq{
Seq: []byte(sequence),
Qual: []byte(quality),
},
}
}
// Test quality metric calculations
func TestQualityMetricCalculations(t *testing.T) {
tests := []struct {
name string
qual []byte
metric QualityMetric
minPhred int
want float64
}{
{
name: "AvgPhred - All high quality",
qual: []byte("IIIII"), // ASCII 73 = Phred 40
metric: AvgPhred,
minPhred: DEFAULT_MIN_PHRED,
want: 40.0,
},
{
name: "AvgPhred - Mixed quality",
qual: []byte("I$$I$"), // Mix of Phred 40 and 3
metric: AvgPhred,
minPhred: DEFAULT_MIN_PHRED,
want: 5.21791,
},
{
name: "AvgPhred - Empty quality",
qual: []byte{},
metric: AvgPhred,
minPhred: DEFAULT_MIN_PHRED,
want: 0.0,
},
{
name: "MaxEE - All high quality",
qual: []byte("IIIII"),
metric: MaxEE,
minPhred: DEFAULT_MIN_PHRED,
want: 0.0005,
},
{
name: "MaxEE - Empty quality",
qual: []byte{},
metric: MaxEE,
minPhred: DEFAULT_MIN_PHRED,
want: math.Inf(1),
},
{
name: "LQCount - No low quality bases",
qual: []byte("IIIII"),
metric: LQCount,
minPhred: 30,
want: 0,
},
{
name: "LQCount - All low quality bases",
qual: []byte("$$$$$"),
metric: LQCount,
minPhred: 30,
want: 5,
},
{
name: "LQPercent - Half low quality bases",
qual: []byte("II$$$"),
metric: LQPercent,
minPhred: 30,
want: 60.0,
},
{
name: "MaxEE - Single very low quality base",
qual: []byte("$"), // ASCII 36 = Phred 3
metric: MaxEE,
minPhred: DEFAULT_MIN_PHRED,
want: 0.5011872336272722, // Error prob for Phred 3
},
{
name: "Meep - Mixed quality",
qual: []byte("I$$I$"), // Mix of Phred 40 and 3
metric: Meep,
minPhred: DEFAULT_MIN_PHRED,
want: 30.07523, // (sum of error probs * 100) / len
},
{
name: "LQCount - Custom minPhred threshold",
qual: []byte("BBBBB"), // ASCII 66 = Phred 33
metric: LQCount,
minPhred: 35,
want: 5, // All bases below Phred 35
},
{
name: "LQPercent - Single base at threshold",
qual: []byte("0"), // ASCII 48 = Phred 15
metric: LQPercent,
minPhred: 15,
want: 0.0, // Base exactly at threshold
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
record := createTestRecord("test", "ACGT", string(tt.qual))
got := calculateQuality(record, tt.metric, tt.minPhred)
// Use approximate comparison for floating point values
if math.Abs(got-tt.want) > 0.00001 {
t.Errorf("calculateQuality() = %v, want %v", got, tt.want)
}
})
}
}
// Test sorting functionality
func TestQualityFloatListSorting(t *testing.T) {
tests := []struct {
name string
items []QualityFloat
ascending bool
metric QualityMetric
want []string // Expected order of names after sorting
}{
{
name: "AvgPhred Descending",
items: []QualityFloat{
{Name: "seq1", Value: 30.0, Metric: AvgPhred},
{Name: "seq2", Value: 40.0, Metric: AvgPhred},
{Name: "seq3", Value: 20.0, Metric: AvgPhred},
},
ascending: false,
metric: AvgPhred,
want: []string{"seq2", "seq1", "seq3"},
},
{
name: "MaxEE Ascending",
items: []QualityFloat{
{Name: "seq1", Value: 0.1, Metric: MaxEE},
{Name: "seq2", Value: 0.01, Metric: MaxEE},
{Name: "seq3", Value: 1.0, Metric: MaxEE},
},
ascending: true,
metric: MaxEE,
want: []string{"seq3", "seq1", "seq2"},
},
{
name: "MaxEE - Equal values, natural sort by name",
items: []QualityFloat{
{Name: "seq10", Value: 0.1, Metric: MaxEE},
{Name: "seq2", Value: 0.1, Metric: MaxEE},
{Name: "seq1", Value: 0.1, Metric: MaxEE},
},
ascending: false,
metric: MaxEE,
want: []string{"seq1", "seq2", "seq10"},
},
{
name: "Meep - Mixed values ascending",
items: []QualityFloat{
{Name: "seq1", Value: 5.0, Metric: Meep},
{Name: "seq2", Value: 2.0, Metric: Meep},
{Name: "seq3", Value: 10.0, Metric: Meep},
},
ascending: true,
metric: Meep,
want: []string{"seq3", "seq1", "seq2"},
},
{
name: "LQPercent - Zero values",
items: []QualityFloat{
{Name: "seq1", Value: 0.0, Metric: LQPercent},
{Name: "seq2", Value: 0.0, Metric: LQPercent},
},
ascending: false,
metric: LQPercent,
want: []string{"seq1", "seq2"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
list := NewQualityFloatList(tt.items, tt.ascending)
sort.Sort(list)
got := make([]string, len(list.items))
for i, item := range list.items {
got[i] = item.Name
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("Sort() got %v, want %v", got, tt.want)
}
})
}
}
// Test header metric parsing
func TestParseHeaderMetrics(t *testing.T) {
tests := []struct {
name string
input string
want []HeaderMetric
wantErr bool
}{
{
name: "Empty string",
input: "",
want: nil,
wantErr: false,
},
{
name: "Valid metrics",
input: "avgphred,maxee,length",
want: []HeaderMetric{
{Name: "avgphred", IsLength: false},
{Name: "maxee", IsLength: false},
{Name: "length", IsLength: true},
},
wantErr: false,
},
{
name: "Invalid metric",
input: "avgphred,invalid,length",
want: nil,
wantErr: true,
},
{
name: "Multiple length metrics",
input: "length,avgphred,length",
want: []HeaderMetric{
{Name: "length", IsLength: true},
{Name: "avgphred", IsLength: false},
{Name: "length", IsLength: true},
},
wantErr: false,
},
{
name: "Whitespace handling",
input: " avgphred , maxee , length ",
want: []HeaderMetric{
{Name: "avgphred", IsLength: false},
{Name: "maxee", IsLength: false},
{Name: "length", IsLength: true},
},
wantErr: false,
},
{
name: "Mixed valid and invalid",
input: "avgphred,invalid1,maxee,invalid2",
want: nil,
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := parseHeaderMetrics(tt.input)
if (err != nil) != tt.wantErr {
t.Errorf("parseHeaderMetrics() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("parseHeaderMetrics() = %v, want %v", got, tt.want)
}
})
}
}
// Test record writing with quality filters
func TestWriteRecord(t *testing.T) {
tests := []struct {
name string
record *fastx.Record
quality float64
minQualFilter float64
maxQualFilter float64
headerMetrics []HeaderMetric
wantWrite bool
wantHeader string
}{
{
name: "Quality within bounds",
record: createTestRecord("test1", "ACGT", "IIII"),
quality: 30.0,
minQualFilter: 20.0,
maxQualFilter: 40.0,
headerMetrics: []HeaderMetric{
{Name: "avgphred", IsLength: false},
{Name: "length", IsLength: true},
},
wantWrite: true,
wantHeader: "test1 avgphred=40.000000 length=4",
},
{
name: "Quality below minimum",
record: createTestRecord("test2", "ACGT", "$$$$"),
quality: 10.0,
minQualFilter: 20.0,
maxQualFilter: 40.0,
wantWrite: false,
wantHeader: "",
},
{
name: "Quality above maximum",
record: createTestRecord("test3", "ACGT", "IIII"),
quality: 45.0,
minQualFilter: 20.0,
maxQualFilter: 40.0,
wantWrite: false,
wantHeader: "",
},
{
name: "No header metrics",
record: createTestRecord("test4", "ACGT", "IIII"),
quality: 30.0,
minQualFilter: 20.0,
maxQualFilter: 40.0,
headerMetrics: nil,
wantWrite: true,
wantHeader: "test4",
},
{
name: "Header with maxee metric",
record: createTestRecord("test5", "ACGT", "IIII"),
quality: 30.0,
minQualFilter: 20.0,
maxQualFilter: 40.0,
headerMetrics: []HeaderMetric{
{Name: "maxee", IsLength: false},
{Name: "length", IsLength: true},
},
wantWrite: true,
wantHeader: "test5 maxee=0.000400 length=4",
},
{
name: "Header with meep metric",
record: createTestRecord("test5", "ACGT", "IIII"),
quality: 30.0,
minQualFilter: 20.0,
maxQualFilter: 40.0,
headerMetrics: []HeaderMetric{
{Name: "meep", IsLength: false},
{Name: "length", IsLength: true},
},
wantWrite: true,
wantHeader: "test5 meep=0.010000 length=4",
},
{
name: "Header with lqpercent metric",
record: createTestRecord("test6", "ACGT", "II$$"),
quality: 30.0,
minQualFilter: 20.0,
maxQualFilter: 40.0,
headerMetrics: []HeaderMetric{
{Name: "lqpercent", IsLength: false},
{Name: "length", IsLength: true},
},
wantWrite: true,
wantHeader: "test6 lqpercent=50.000000 length=4",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Create a temporary file for testing
tmpfile, err := os.CreateTemp("", "test*.fastq")
if err != nil {
t.Fatal(err)
}
defer os.Remove(tmpfile.Name())
defer tmpfile.Close()
// Create writer using the temp file
writer, err := xopen.Wopen(tmpfile.Name())
if err != nil {
t.Fatal(err)
}
defer writer.Close()
// Test writeRecord
got := writeRecord(writer, tt.record, tt.quality, tt.headerMetrics, AvgPhred, DEFAULT_MIN_PHRED, tt.minQualFilter, tt.maxQualFilter)
if got != tt.wantWrite {
t.Errorf("writeRecord() = %v, want %v", got, tt.wantWrite)
}
// If the record should be written, verify the header
if tt.wantWrite {
// Close the writer to ensure all data is written
writer.Close()
// Read the file content
content, err := os.ReadFile(tmpfile.Name())
if err != nil {
t.Fatal(err)
}
// Extract the header from the FASTQ format (first line)
lines := strings.Split(string(content), "\n")
if len(lines) > 0 {
gotHeader := strings.TrimPrefix(lines[0], "@")
if gotHeader != tt.wantHeader {
t.Errorf("Header = %q, want %q", gotHeader, tt.wantHeader)
}
}
}
})
}
}
// Test quality metric string representation
func TestQualityMetricString(t *testing.T) {
tests := []struct {
metric QualityMetric
want string
}{
{AvgPhred, "avgphred"},
{MaxEE, "maxee"},
{Meep, "meep"},
{LQCount, "lqcount"},
{LQPercent, "lqpercent"},
{QualityMetric(999), "unknown"},
}
for _, tt := range tests {
t.Run(tt.want, func(t *testing.T) {
if got := tt.metric.String(); got != tt.want {
t.Errorf("QualityMetric.String() = %v, want %v", got, tt.want)
}
})
}
}
// Add test for error probability initialization
func TestErrorProbabilitiesInit(t *testing.T) {
// Test a few key values from the pre-computed errorProbs array
tests := []struct {
phred byte
want float64
}{
{33, 1}, // Phred 0 (33 - 33 = 0)
{43, 0.1}, // Phred 10 (43 - 33 = 10)
{53, 0.01}, // Phred 20 (53 - 33 = 20)
{63, 0.001}, // Phred 30 (63 - 33 = 30)
{73, 0.0001}, // Phred 40 (73 - 33 = 40)
{83, 0.00001}, // Phred 50 (83 - 33 = 50)
{93, 0.000001}, // Phred 60 (93 - 33 = 60)
}
for _, tt := range tests {
t.Run(fmt.Sprintf("Phred%d", tt.phred-PHRED_OFFSET), func(t *testing.T) {
if got := errorProbs[tt.phred]; math.Abs(got-tt.want) > 1e-10 {
t.Errorf("errorProbs[%d] = %v, want %v", tt.phred, got, tt.want)
}
})
}
}
// TestSortFile tests the file-based sorting functionality
func TestSortFile(t *testing.T) {
tests := []struct {
name string
records []*fastx.Record
metric QualityMetric
ascending bool
headerMetrics []HeaderMetric
minPhred int
minQual float64
maxQual float64
wantOrder []string
wantErr bool
}{
{
name: "Basic sorting by AvgPhred descending",
records: []*fastx.Record{
createTestRecord("seq1", "ACGT", "IIII"), // Phred 40
createTestRecord("seq2", "ACGT", "$$$$"), // Phred 3
createTestRecord("seq3", "ACGT", "@@@@"), // Phred 31
},
metric: AvgPhred,
ascending: false,
minPhred: DEFAULT_MIN_PHRED,
minQual: 0.0, // Allow all quality scores
maxQual: math.Inf(1), // Allow all quality scores
wantOrder: []string{"seq1", "seq3", "seq2"},
},
{
name: "MaxEE ascending with quality filters",
records: []*fastx.Record{
createTestRecord("seq1", "ACGT", "IIII"), // Very low MaxEE
createTestRecord("seq2", "ACGT", "$$$$"), // Very high MaxEE
createTestRecord("seq3", "ACGT", "@@@@"), // Medium MaxEE
},
metric: MaxEE,
ascending: true,
minPhred: DEFAULT_MIN_PHRED,
minQual: 0.0,
maxQual: 1.0, // Should filter out seq2
wantOrder: []string{"seq3", "seq1"},
},
{
name: "LQCount with header metrics",
records: []*fastx.Record{
createTestRecord("seq1", "ACGT", "III$"), // 1 low quality out of 4
createTestRecord("seq2", "ACGTAA", "$$$$$$"), // all 6 low quality
createTestRecord("seq3", "ACGT", "&&&@"), // 3 low quality out of 4
},
metric: LQCount,
ascending: false,
headerMetrics: []HeaderMetric{
{Name: "lqcount", IsLength: false},
{Name: "length", IsLength: true},
},
minPhred: 30,
minQual: 0.0,
maxQual: math.Inf(1),
wantOrder: []string{"seq1", "seq3", "seq2"},
},
{
name: "Natural sort on equal values",
records: []*fastx.Record{
createTestRecord("seq2", "ACGT", "IIII"),
createTestRecord("seq10", "ACGT", "IIII"),
createTestRecord("seq1", "ACGT", "IIII"),
},
metric: AvgPhred,
ascending: false,
minPhred: DEFAULT_MIN_PHRED,
minQual: 0.0,
maxQual: math.Inf(1),
wantOrder: []string{"seq1", "seq2", "seq10"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Create temporary input and output files
inFile, err := os.CreateTemp("", "test_in_*.fastq")
if err != nil {
t.Fatal(err)
}
defer os.Remove(inFile.Name())
outFile, err := os.CreateTemp("", "test_out_*.fastq")
if err != nil {
t.Fatal(err)
}
defer os.Remove(outFile.Name())
// Write test records to input file
writer, err := xopen.Wopen(inFile.Name())
if err != nil {
t.Fatal(err)
}
// Write records in FASTQ format
for _, record := range tt.records {
fmt.Fprintf(writer, "@%s\n%s\n+\n%s\n",
record.Name,
record.Seq.Seq,
record.Seq.Qual)
}
writer.Close()
// Run sortFile
sortFile(
inFile.Name(),
outFile.Name(),
tt.ascending,
tt.metric,
tt.headerMetrics,
tt.minPhred,
tt.minQual,
tt.maxQual,
)
// Read and verify output
reader, err := fastx.NewReader(seq.DNAredundant, outFile.Name(), fastx.DefaultIDRegexp)
if err != nil {
t.Fatal(err)
}
defer reader.Close()
var gotOrder []string
for {
record, err := reader.Read()
if err == io.EOF {
break
}
if err != nil {
t.Fatal(err)
}
name := strings.Split(string(record.Name), " ")[0]
gotOrder = append(gotOrder, name)
}
// Only show file contents if there's a test failure
if len(gotOrder) == 0 || !reflect.DeepEqual(gotOrder, tt.wantOrder) {
// Read and log input file contents
inContent, err := os.ReadFile(inFile.Name())
if err != nil {
t.Logf("Failed to read input file: %v", err)
} else {
t.Logf("Input file contents:\n%s", string(inContent))
}
// Read and log output file contents
outContent, err := os.ReadFile(outFile.Name())
if err != nil {
t.Logf("Failed to read output file: %v", err)
} else {
t.Logf("Output file contents:\n%s", string(outContent))
}
}
if len(gotOrder) == 0 {
t.Error("No records were read from the output file")
}
if !reflect.DeepEqual(gotOrder, tt.wantOrder) {
t.Errorf("sortFile() got order = %v, want %v", gotOrder, tt.wantOrder)
}
// If header metrics were specified, verify they were added correctly
if len(tt.headerMetrics) > 0 {
reader, _ = fastx.NewReader(seq.DNAredundant, outFile.Name(), fastx.DefaultIDRegexp)
record, _ := reader.Read()
header := string(record.Name)
// Check that all requested metrics are present
for _, metric := range tt.headerMetrics {
if metric.IsLength {
if !strings.Contains(header, "length=") {
t.Errorf("Header missing length metric: %s", header)
}
} else {
if !strings.Contains(header, metric.Name+"=") {
t.Errorf("Header missing metric %s: %s", metric.Name, header)
}
}
}
}
})
}
}
// TestSortStdin tests the stdin-based sorting functionality
func TestSortStdin(t *testing.T) {
tests := []struct {
name string
records []*fastx.Record
metric QualityMetric
ascending bool
compLevel int
headerMetrics []HeaderMetric
minPhred int
minQual float64
maxQual float64
wantOrder []string
wantErr bool
}{
{
name: "Basic sorting with compression",
records: []*fastx.Record{
createTestRecord("seq1", "ACGT", "IIII"), // Phred 40
createTestRecord("seq2", "ACGT", "$$$$"), // Phred 3
createTestRecord("seq3", "ACGT", "@@@@"), // Phred 31
},
metric: AvgPhred,
ascending: false,
compLevel: 1,
minPhred: DEFAULT_MIN_PHRED,
minQual: 0.0,
maxQual: math.Inf(1),
wantOrder: []string{"seq1", "seq3", "seq2"},
},
{
name: "Sorting with quality filters",
records: []*fastx.Record{
createTestRecord("seq1", "ACGT", "IIII"), // Phred 40
createTestRecord("seq2", "ACGT", "$$$$"), // Phred 3
createTestRecord("seq3", "ACGT", "@@@@"), // Phred 31
},
metric: AvgPhred,
ascending: false,
compLevel: 0, // No compression
minPhred: DEFAULT_MIN_PHRED,
minQual: 30.0, // Only keep sequences with AvgPhred >= 30
maxQual: 35.0, // Only keep sequences with AvgPhred <= 35
wantOrder: []string{"seq3"}, // Only seq3 falls within the quality range
},
{
name: "Sorting with header metrics",
records: []*fastx.Record{
createTestRecord("seq1", "ACGT", "IIII"),
createTestRecord("seq2", "ACGTAA", "$$$$$$"),
},
metric: AvgPhred,
ascending: false,
compLevel: 1,
headerMetrics: []HeaderMetric{
{Name: "avgphred", IsLength: false},
{Name: "length", IsLength: true},
},
minPhred: DEFAULT_MIN_PHRED,
minQual: 0.0,
maxQual: math.Inf(1),
wantOrder: []string{"seq1", "seq2"},
},
{
name: "Natural sort with equal qualities",
records: []*fastx.Record{
createTestRecord("seq2", "ACGT", "IIII"),
createTestRecord("seq10", "ACGT", "IIII"),
createTestRecord("seq1", "ACGT", "IIII"),
},
metric: AvgPhred,
ascending: false,
compLevel: 1,
minPhred: DEFAULT_MIN_PHRED,
minQual: 0.0,
maxQual: math.Inf(1),
wantOrder: []string{"seq1", "seq2", "seq10"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Create temporary input and output files
tmpInFile, err := os.CreateTemp("", "test_stdin_*.fastq")
if err != nil {
t.Fatal(err)
}
defer os.Remove(tmpInFile.Name())
tmpOutFile, err := os.CreateTemp("", "test_stdout_*.fastq")
if err != nil {
t.Fatal(err)
}
defer os.Remove(tmpOutFile.Name())
// Write test records to input file
for _, record := range tt.records {
fmt.Fprintf(tmpInFile, "@%s\n%s\n+\n%s\n",
record.Name,
record.Seq.Seq,
record.Seq.Qual)
}
tmpInFile.Close()
// Redirect stdin to read from the temp file
oldStdin := os.Stdin
newStdin, err := os.Open(tmpInFile.Name())
if err != nil {
t.Fatal(err)
}
os.Stdin = newStdin
defer func() {
os.Stdin = oldStdin
newStdin.Close()
}()
// Run sortStdin
sortStdin(
tmpOutFile.Name(),
tt.ascending,
tt.metric,
tt.compLevel,
tt.headerMetrics,
tt.minPhred,
tt.minQual,
tt.maxQual,
)
// Read and verify output
reader, err := fastx.NewReader(seq.DNAredundant, tmpOutFile.Name(), fastx.DefaultIDRegexp)
if err != nil {
t.Fatal(err)
}
defer reader.Close()
var gotOrder []string
for {
record, err := reader.Read()
if err == io.EOF {
break
}
if err != nil {
t.Fatal(err)
}
name := strings.Split(string(record.Name), " ")[0] // Extract base name without metrics
gotOrder = append(gotOrder, name)
}
// Verify the results
if len(gotOrder) != len(tt.wantOrder) {
t.Errorf("Got %d records, want %d records", len(gotOrder), len(tt.wantOrder))
}
if !reflect.DeepEqual(gotOrder, tt.wantOrder) {
t.Errorf("sortStdin() got order = %v, want %v", gotOrder, tt.wantOrder)
}
// If header metrics were specified, verify they were added correctly
if len(tt.headerMetrics) > 0 {
reader, _ = fastx.NewReader(seq.DNAredundant, tmpOutFile.Name(), fastx.DefaultIDRegexp)
record, _ := reader.Read()
header := string(record.Name)
// Check that all requested metrics are present
for _, metric := range tt.headerMetrics {
if metric.IsLength {
if !strings.Contains(header, "length=") {
t.Errorf("Header missing length metric: %s", header)
}
} else {
if !strings.Contains(header, metric.Name+"=") {
t.Errorf("Header missing metric %s: %s", metric.Name, header)
}
}
}
}
})
}
}
// TestMainCommand tests the main command functionality
func TestMainCommand(t *testing.T) {
// Create temporary directory for test files
tmpDir, err := os.MkdirTemp("", "phredsort_test_*")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpDir)
// Helper function to create test FASTQ file
createTestFastq := func(name string) string {
path := filepath.Join(tmpDir, name)
f, err := os.Create(path)
if err != nil {
t.Fatal(err)
}
defer f.Close()
// Write some test FASTQ data
fmt.Fprintf(f, "@seq1\nACGT\n+\nIIII\n")
fmt.Fprintf(f, "@seq2\nACGT\n+\n$$$$\n")
return path
}
// Helper function to capture stdout/stderr
captureOutput := func(f func()) (string, string) {
oldStdout := os.Stdout
oldStderr := os.Stderr
rOut, wOut, _ := os.Pipe()
rErr, wErr, _ := os.Pipe()
os.Stdout = wOut
os.Stderr = wErr
f()
wOut.Close()
wErr.Close()
os.Stdout = oldStdout
os.Stderr = oldStderr
stdout, _ := io.ReadAll(rOut)
stderr, _ := io.ReadAll(rErr)
return string(stdout), string(stderr)
}
tests := []struct {
name string
args []string
expectedCode int
checkStdout bool
checkStderr bool
wantStdout string
wantStderr string
setupFiles bool
validateFiles bool
}{
{
name: "Version flag",
args: []string{"--version"},
expectedCode: 0,
checkStdout: true,
wantStdout: fmt.Sprintf("phredsort %s\n", VERSION),
},
{
name: "Missing required flags",
args: []string{},
expectedCode: 1,
checkStderr: true,
wantStderr: red("Error: input and output files are required") + "\n" +
red("Try 'phredsort --help' for more information") + "\n",
},
{
name: "Invalid metric",
args: []string{"--in", "input.fq", "--out", "output.fq", "--metric", "invalid"},
expectedCode: 1,
checkStderr: true,
wantStderr: red("Error: invalid metric 'invalid'. Must be one of: avgphred, maxee, meep, lqcount, lqpercent"),
},
{
name: "Invalid compression level",
args: []string{"--in", "input.fq", "--out", "output.fq", "--compress", "23"},
expectedCode: 1,
checkStderr: true,
wantStderr: red("Error: compression level must be between 0 and 22") + "\n",
},
{
name: "Invalid header metrics",
args: []string{"--in", "input.fq", "--out", "output.fq", "--header", "invalid,metrics"},
expectedCode: 1,
checkStderr: true,
wantStderr: red("Error: invalid header metric: invalid") + "\n",
},
{
name: "Basic file processing",
args: []string{"--in", "input.fq", "--out", "output.fq"},
expectedCode: 0,
setupFiles: true,
validateFiles: true,
},
{
name: "Complex command with multiple options",
args: []string{
"--in", "input.fq",
"--out", "output.fq",
"--metric", "avgphred",
"--minphred", "20",
"--minqual", "15",
"--maxqual", "40",
"--header", "avgphred,maxee,length",
"--ascending",
"--compress", "1",
},
expectedCode: 0,
setupFiles: true,
validateFiles: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.setupFiles {
inFile := createTestFastq("input.fq")
outFile := filepath.Join(tmpDir, "output.fq")
// Update args with actual file paths
for i, arg := range tt.args {
switch arg {
case "input.fq":
tt.args[i] = inFile
case "output.fq":
tt.args[i] = outFile
}
}
}
// Reset os.Args and set test arguments
oldArgs := os.Args
os.Args = append([]string{"phredsort"}, tt.args...)
// Capture exit code
var exitCode int
oldExit := exitFunc
exitFunc = func(code int) {
exitCode = code
panic(fmt.Sprintf("exit %d", code))
}
defer func() {
exitFunc = oldExit
os.Args = oldArgs