Repository navigation
Expand file tree
/
Copy pathseqhasher_test.go
More file actions
740 lines (685 loc) · 23.1 KB
/
Copy pathseqhasher_test.go
File metadata and controls
740 lines (685 loc) · 23.1 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
package main
import (
"bytes"
"errors"
"flag"
"fmt"
"io"
"io/fs"
"log"
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"github.com/shenwei356/bio/seq"
)
const (
testFastaPath = "./test/test.fasta"
// Content of testFastaPath (and its compressed versions)
testSequences = ">seq1\nACTG\n>seq1_lowercase\nactg\n>seq2\nTGCA\n"
)
// setArgs replaces os.Args and the global FlagSet for the duration of a test
func setArgs(t *testing.T, args ...string) {
t.Helper()
oldArgs, oldCommandLine, oldUsage := os.Args, flag.CommandLine, flag.Usage
t.Cleanup(func() {
os.Args, flag.CommandLine, flag.Usage = oldArgs, oldCommandLine, oldUsage
})
os.Args = args
flag.CommandLine = flag.NewFlagSet(args[0], flag.ContinueOnError)
}
// setStdin replaces os.Stdin with a file containing the given data for the duration of a test
func setStdin(t *testing.T, data string) {
t.Helper()
path := filepath.Join(t.TempDir(), "stdin.fasta")
if err := os.WriteFile(path, []byte(data), 0o644); err != nil {
t.Fatal(err)
}
f, err := os.Open(path)
if err != nil {
t.Fatal(err)
}
oldStdin := os.Stdin
os.Stdin = f
t.Cleanup(func() {
os.Stdin = oldStdin
_ = f.Close()
})
}
// process runs processSequences on the input string and returns the output
func process(t *testing.T, input string, cfg config) string {
t.Helper()
var out bytes.Buffer
if err := processSequences(strings.NewReader(input), &out, cfg); err != nil {
t.Fatalf("processSequences() unexpected error: %v", err)
}
return out.String()
}
func TestParseFlags(t *testing.T) {
tests := []struct {
name string
args []string
expected config
expectedErrMsg string
}{
{
name: "Default settings",
args: []string{"cmd", "input.fasta"},
expected: config{
hashTypes: []string{"sha1"},
inputFileName: "input.fasta",
},
},
{
name: "Custom settings",
args: []string{"cmd", "-headersonly", "-hash", "md5", "-nofilename", "-casesensitive", "input.fasta", "output.fasta"},
expected: config{
headersOnly: true,
hashTypes: []string{"md5"},
noFileName: true,
caseSensitive: true,
inputFileName: "input.fasta",
outputFileName: "output.fasta",
},
},
{
name: "Shorthand flags",
args: []string{"cmd", "-o", "-H", "blake3", "-n", "-c", "-f", "sample", "-", "-"},
expected: config{
headersOnly: true,
hashTypes: []string{"blake3"},
noFileName: true,
caseSensitive: true,
nameOverride: "sample",
inputFileName: "-",
outputFileName: "-",
},
},
{
name: "Multiple hash types",
args: []string{"cmd", "-hash", "sha1,xxhash", "input.fasta"},
expected: config{
hashTypes: []string{"sha1", "xxhash"},
inputFileName: "input.fasta",
},
},
{
name: "Version",
args: []string{"cmd", "--version"},
expected: config{
hashTypes: []string{"sha1"},
showVersion: true,
},
},
{
name: "Invalid hash type",
args: []string{"cmd", "-hash", "invalid,sha1", "input.fasta"},
expectedErrMsg: "invalid hash type: invalid. Supported types are: sha1, sha3, md5, xxhash, xxh3, cityhash, murmur3, nthash, blake3, k12, rapidhash, rapidhash32",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
setArgs(t, tt.args...)
cfg, err := parseFlags()
if tt.expectedErrMsg != "" {
if err == nil {
t.Fatalf("expected error %q, got nil", tt.expectedErrMsg)
}
if err.Error() != tt.expectedErrMsg {
t.Errorf("error = %q, want %q", err.Error(), tt.expectedErrMsg)
}
return
}
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !reflect.DeepEqual(cfg, tt.expected) {
t.Errorf("parseFlags() = %+v, want %+v", cfg, tt.expected)
}
})
}
}
func TestIsValidHashType(t *testing.T) {
for _, ht := range supportedHashTypes {
if !isValidHashType(ht) {
t.Errorf("isValidHashType(%q) = false, want true", ht)
}
}
for _, ht := range []string{"invalid", "", "SHA1", " sha1", "sha256"} {
if isValidHashType(ht) {
t.Errorf("isValidHashType(%q) = true, want false", ht)
}
}
}
func TestGetInput(t *testing.T) {
t.Run("Stdin", func(t *testing.T) {
input, err := getInput("-")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if input != os.Stdin {
t.Errorf(`getInput("-") did not return os.Stdin`)
}
})
t.Run("Existing file", func(t *testing.T) {
input, err := getInput(testFastaPath)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
defer func() { _ = input.Close() }()
data, err := io.ReadAll(input)
if err != nil {
t.Fatalf("failed to read input: %v", err)
}
if string(data) != testSequences {
t.Errorf("unexpected content of %s: %q", testFastaPath, data)
}
})
t.Run("Non-existent file", func(t *testing.T) {
_, err := getInput(filepath.Join(t.TempDir(), "nonexistent.fasta"))
if !errors.Is(err, fs.ErrNotExist) {
t.Errorf("expected fs.ErrNotExist, got %v", err)
}
})
}
func TestGetOutput(t *testing.T) {
t.Run("Stdout", func(t *testing.T) {
output, err := getOutput("-")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if output != os.Stdout {
t.Errorf(`getOutput("-") did not return os.Stdout`)
}
})
t.Run("New file", func(t *testing.T) {
path := filepath.Join(t.TempDir(), "out.fasta")
output, err := getOutput(path)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if err := output.Close(); err != nil {
t.Fatalf("failed to close output: %v", err)
}
if _, err := os.Stat(path); err != nil {
t.Errorf("output file was not created: %v", err)
}
})
t.Run("Directory", func(t *testing.T) {
if _, err := getOutput(t.TempDir()); err == nil {
t.Error("expected an error when writing to a directory, got nil")
}
})
}
func TestProcessSequences(t *testing.T) {
tests := []struct {
name string
input string
cfg config
expected string
}{
{
name: "Default settings",
input: testSequences,
cfg: config{hashTypes: []string{"sha1"}, inputFileName: "test.fasta"},
expected: ">test.fasta;65c89f59d38cdbf90dfaf0b0a6884829df8396b0;seq1\nACTG\n" +
">test.fasta;65c89f59d38cdbf90dfaf0b0a6884829df8396b0;seq1_lowercase\nACTG\n" +
">test.fasta;e3da52abc8fbdb38b113a187ed0ac763fa86d1d4;seq2\nTGCA\n",
},
{
name: "Headers only",
input: testSequences,
cfg: config{headersOnly: true, hashTypes: []string{"md5"}, noFileName: true, inputFileName: "test.fasta"},
expected: "86bfb9f78dd8b6cd35962bb7324fdbf8;seq1\n" +
"86bfb9f78dd8b6cd35962bb7324fdbf8;seq1_lowercase\n" +
"5c15f97a88433c48f8bf76745d9da437;seq2\n",
},
{
name: "ntHash",
input: testSequences,
cfg: config{hashTypes: []string{"nthash"}, inputFileName: "test.fasta"},
expected: ">test.fasta;508876b331232519;seq1\nACTG\n" +
">test.fasta;508876b331232519;seq1_lowercase\nACTG\n" +
">test.fasta;95cecc5106c8fccd;seq2\nTGCA\n",
},
{
name: "Case-sensitive",
input: testSequences,
cfg: config{headersOnly: true, hashTypes: []string{"sha1"}, noFileName: true, caseSensitive: true},
expected: "65c89f59d38cdbf90dfaf0b0a6884829df8396b0;seq1\n" +
"80a8d5427ee0f280d9d7ec809b7184e12959b85b;seq1_lowercase\n" +
"e3da52abc8fbdb38b113a187ed0ac763fa86d1d4;seq2\n",
},
{
name: "Multiple hash types and name override",
input: ">seq1\nACTG\n",
cfg: config{hashTypes: []string{"sha1", "xxhash"}, inputFileName: "test.fasta", nameOverride: "sample"},
expected: ">sample;65c89f59d38cdbf90dfaf0b0a6884829df8396b0;704b34bf20faedf2;seq1\nACTG\n",
},
{
name: "Stdin input omits file name",
input: ">seq1\nACTG\n",
cfg: config{hashTypes: []string{"sha1"}, inputFileName: "-"},
expected: ">65c89f59d38cdbf90dfaf0b0a6884829df8396b0;seq1\nACTG\n",
},
{
name: "Stdin input with name override",
input: ">seq1\nACTG\n",
cfg: config{hashTypes: []string{"sha1"}, inputFileName: "-", nameOverride: "sample"},
expected: ">sample;65c89f59d38cdbf90dfaf0b0a6884829df8396b0;seq1\nACTG\n",
},
{
name: "Header description is preserved",
input: ">seq1 sample=A1 len=4\nACTG\n",
cfg: config{headersOnly: true, hashTypes: []string{"sha1"}, noFileName: true},
expected: "65c89f59d38cdbf90dfaf0b0a6884829df8396b0;seq1 sample=A1 len=4\n",
},
{
name: "Multi-line sequence and CRLF line endings",
input: ">seq1\r\nAC\r\nTG\r\n>seq2\r\nTGCA\r\n",
cfg: config{hashTypes: []string{"sha1"}, noFileName: true},
expected: ">65c89f59d38cdbf90dfaf0b0a6884829df8396b0;seq1\nACTG\n>e3da52abc8fbdb38b113a187ed0ac763fa86d1d4;seq2\nTGCA\n",
},
{
name: "Whitespace within sequence",
input: ">seq1\nAC TG \n>seq2\nAC\tTG\n",
cfg: config{headersOnly: true, hashTypes: []string{"sha1"}, noFileName: true},
expected: "65c89f59d38cdbf90dfaf0b0a6884829df8396b0;seq1\n65c89f59d38cdbf90dfaf0b0a6884829df8396b0;seq2\n",
},
{
name: "Non-DNA characters (no validation)",
input: ">seq1\nACTGINVALID\n",
cfg: config{hashTypes: []string{"sha1"}, inputFileName: "test.fasta"},
expected: ">test.fasta;3e06752b63358c1a14c4c364513cbc2250674bb8;seq1\nACTGINVALID\n",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := process(t, tt.input, tt.cfg); got != tt.expected {
t.Errorf("config: %+v\ngot:\n%s\nwant:\n%s", tt.cfg, got, tt.expected)
}
})
}
}
func TestProcessFASTQSequences(t *testing.T) {
const input = "@seq1\nACTG\n+\nDFGH\n@seq2\nAAAA\n+\nBBBB\n"
tests := []struct {
name string
cfg config
expected string
}{
{
name: "Basic FASTQ processing",
cfg: config{hashTypes: []string{"sha1"}, inputFileName: "test.fastq"},
expected: "@test.fastq;65c89f59d38cdbf90dfaf0b0a6884829df8396b0;seq1\nACTG\n+\nDFGH\n" +
"@test.fastq;e2512172abf8cc9f67fdd49eb6cacf2df71bbad3;seq2\nAAAA\n+\nBBBB\n",
},
{
name: "FASTQ with headers only",
cfg: config{headersOnly: true, hashTypes: []string{"sha1"}, noFileName: true, inputFileName: "test.fastq"},
expected: "65c89f59d38cdbf90dfaf0b0a6884829df8396b0;seq1\n" +
"e2512172abf8cc9f67fdd49eb6cacf2df71bbad3;seq2\n",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := process(t, input, tt.cfg); got != tt.expected {
t.Errorf("got:\n%s\nwant:\n%s", got, tt.expected)
}
})
}
}
func TestProcessFastaAfterFastq(t *testing.T) {
// fastx pools readers and records; a FASTA file processed after a FASTQ file
// must not inherit quality scores (otherwise, it would be written as FASTQ)
cfg := config{hashTypes: []string{"sha1"}, noFileName: true}
if got := process(t, "@s1\nACTG\n+\nIIII\n", cfg); !strings.HasPrefix(got, "@") {
t.Fatalf("expected FASTQ output, got %q", got)
}
want := ">65c89f59d38cdbf90dfaf0b0a6884829df8396b0;s1\nACTG\n"
if got := process(t, ">s1\nACTG\n", cfg); got != want {
t.Errorf("got %q, want %q", got, want)
}
}
func TestProcessFASTQEmptySequence(t *testing.T) {
// FASTQ records with empty sequences must be written as FASTQ (not as FASTA)
oldLogOutput := log.Writer()
log.SetOutput(io.Discard)
defer log.SetOutput(oldLogOutput)
got := process(t, "@a\n\n+\n\n@b\nAC\n+\nII\n", config{hashTypes: []string{"sha1"}, noFileName: true})
want := "@;a\n\n+\n\n@b1fb3bec6fdb22e19a94fe4c6c4481ccba2ee9f0;b\nAC\n+\nII\n"
if got != want {
t.Errorf("got %q, want %q", got, want)
}
}
func TestProcessSequencesValidationDisabled(t *testing.T) {
// processSequences must accept non-IUPAC characters,
// regardless of the global validation setting of the `bio` library
old := seq.ValidateSeq
seq.ValidateSeq = true
defer func() { seq.ValidateSeq = old }()
got := process(t, ">seq1\nAC!@#TG123\n", config{headersOnly: true, hashTypes: []string{"md5"}, noFileName: true})
want := fmt.Sprintf("%s;seq1\n", getHashFunc("md5")([]byte("AC!@#TG123")))
if got != want {
t.Errorf("got %q, want %q", got, want)
}
}
// failingReader is an io.Reader that returns content which is not FASTA/FASTQ
type failingReader struct{}
func (failingReader) Read(p []byte) (int, error) {
n := copy(p, "invalid input")
return n, io.EOF
}
func TestProcessSequencesInvalidFormat(t *testing.T) {
err := processSequences(failingReader{}, io.Discard, config{hashTypes: []string{"sha1"}, inputFileName: "test.fasta"})
if err == nil {
t.Fatal("expected an error, got nil")
}
if !strings.Contains(err.Error(), "fastx: invalid FASTA/Q format") {
t.Errorf("unexpected error: %v", err)
}
}
// failingWriter is an io.Writer that always fails
type failingWriter struct{}
func (failingWriter) Write([]byte) (int, error) { return 0, errors.New("disk full") }
func TestProcessSequencesWriteError(t *testing.T) {
// Large enough input to overflow the bufio.Writer buffer
input := strings.Repeat(">seq\nACGTACGTACGTACGTACGTACGTACGTACGTACGTACGT\n", 1000)
err := processSequences(strings.NewReader(input), failingWriter{}, config{hashTypes: []string{"sha1"}})
if err == nil || !strings.Contains(err.Error(), "disk full") {
t.Errorf("expected write error, got %v", err)
}
}
func TestGetHashFunc(t *testing.T) {
// Golden values; any change indicates that hashes are no longer
// compatible with the previous versions of SeqHasher.
// (sha1, md5 and sha3 values were cross-checked with sha1sum, md5sum and `openssl dgst -sha3-512`;
// the other values pin the output of the current implementation)
const longSeq = "GATTACAACGTNNNNACGTRYKMSWBDHVGGCCTTAAGGCATGCATGCAAATTTGGGCCCACGT"
tests := []struct {
hashType string
short string // hash of "ACTG"
long string // hash of longSeq
}{
{"sha1",
"65c89f59d38cdbf90dfaf0b0a6884829df8396b0",
"5a4308377605ca5812cc71d8e6cfe4e3e8a2a6ac"},
{"sha3",
"01eb915e4d8b6d44d0432c12dfdb949c1da1f37c295a653b8761a1e46ed2d76cb0c297d612af809b9691d341cad536df912cbba6e95a93380cdc9f545d9bfdcc",
"1f8bc5c14c6ed19b6ee66d90f52f1077507dc3ff7112d354f99f952a278d9fbc39d9855381d7fae7e7de4c51a48cd73755d42457e52864b4e7e13b9298c5037e"},
{"md5",
"86bfb9f78dd8b6cd35962bb7324fdbf8",
"c7ccbf1e13a9da54efbcff7184053fcf"},
{"xxhash",
"704b34bf20faedf2",
"b21ab8b1eefc36be"},
{"xxh3",
"623952c8b43f0072",
"12f6e04ccc83b107"},
{"cityhash",
"7ee08b0605f909cf400644ddb3b8b80b",
"e162c0806edd65e37a59bbb32397490e"},
{"murmur3",
"da48f168029d0eff17c81eff7624a72f",
"2ef3e3b32e7e35cd29f9d477ed1be80b"},
{"nthash",
"508876b331232519",
"9b72ece692614ffd"},
{"blake3",
"fe31e49d18b8883e7167198f770b98bba33b533cc12a9bb63ab264e5b70a347a",
"750b7f59a606f13810f9ed18c65be6daf7ac4c06d840996c7b93c4e5139bee23"},
{"k12",
"9985653b7671edf4d1194c22886e3d1324c5ab28768c83e684387aea98c39ca0bceef0014d42ef5a3021b0686c5377529796e36401de254c977e14d59ca9d64ae567d568cd0f63f022a37b9678ac329d874860182f9e20fef9adeb0d3057c93b4f36386234798acfb94f469bee78baac64911e5ae1294db2b86aea32c5b3be12",
"70e18932805d9fa4fe3b51e1daf8779b45f1e0260300dff75429fcc0c6e26d3a6381e7e3749d5f35995d8f4b039736a138a9be4216a23c0393e7cb741c4fb1b06355fbaa4a92ad7172011ceb51e073fe5a4ed620b78eb9dbb0299b127485365a8d538cbe6d4f507e7cd00e408ad543416e79fde2c52958e51bd454b60bf09d95"},
{"rapidhash",
"e5ba56a5fa8a1dcf",
"fe2296bab607f24a"},
{"rapidhash32",
"1f304b6a",
"482564f0"},
}
if len(tests) != len(supportedHashTypes) {
t.Fatalf("golden values are missing for some hash types (have %d, supported %d)", len(tests), len(supportedHashTypes))
}
for _, tt := range tests {
t.Run(tt.hashType, func(t *testing.T) {
hashFunc := getHashFunc(tt.hashType)
if got := hashFunc([]byte("ACTG")); got != tt.short {
t.Errorf("ACTG: got %s, want %s", got, tt.short)
}
if got := hashFunc([]byte(longSeq)); got != tt.long {
t.Errorf("long sequence: got %s, want %s", got, tt.long)
}
})
}
}
func TestCompressedInput(t *testing.T) {
expected := "65c89f59d38cdbf90dfaf0b0a6884829df8396b0;seq1\n" +
"65c89f59d38cdbf90dfaf0b0a6884829df8396b0;seq1_lowercase\n" +
"e3da52abc8fbdb38b113a187ed0ac763fa86d1d4;seq2\n"
cfg := config{hashTypes: []string{"sha1"}, noFileName: true, headersOnly: true}
for _, ext := range []string{"", ".gz", ".bz2", ".xz", ".zst"} {
fileName := testFastaPath + ext
t.Run(filepath.Base(fileName), func(t *testing.T) {
setArgs(t, "seqhasher", "-n", "-o", fileName)
var out bytes.Buffer
if err := run(&out); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got := out.String(); got != expected {
t.Errorf("got:\n%s\nwant:\n%s", got, expected)
}
})
}
// Uncompressed data read through a plain io.Reader
t.Run("io.Reader", func(t *testing.T) {
if got := process(t, testSequences, cfg); got != expected {
t.Errorf("got:\n%s\nwant:\n%s", got, expected)
}
})
}
func TestTestDataFiles(t *testing.T) {
tests := []struct {
file string
expected string
}{
{
file: "./test/seqs_with_spaces.fasta",
expected: "65c89f59d38cdbf90dfaf0b0a6884829df8396b0;seq1_uppercase\n" +
"65c89f59d38cdbf90dfaf0b0a6884829df8396b0;seq2_lowercase\n" +
"65c89f59d38cdbf90dfaf0b0a6884829df8396b0;seq3_mixed_case\n" +
"65c89f59d38cdbf90dfaf0b0a6884829df8396b0;seq4_with_spaces\n" +
"65c89f59d38cdbf90dfaf0b0a6884829df8396b0;seq5_with_tabs\n" +
"65c89f59d38cdbf90dfaf0b0a6884829df8396b0;seq6_with_newline\n",
},
{
file: "./test/problematic_sequences.fasta",
expected: "76a2743bc120793fa6498c881f79f175d80106aa;seq_with_numbers123\n" +
"5c8a1ef18f0ebf4876b072f9133b0b3d74b925fd;seq_with_non_dna_bases\n" +
"ada3ee6a33271e6c564d8c8f646195b86a4b3b08;seq_with_iupac_bases\n" +
"8459ee6c5d718b1db8ba43cc82cbeeb14182bf69;seq_special_chars\n" +
";seq_empty\n",
},
{
file: "./test/test3.fastq", // no trailing newline
expected: "65c89f59d38cdbf90dfaf0b0a6884829df8396b0;seq1\n" +
"e2512172abf8cc9f67fdd49eb6cacf2df71bbad3;seq2\n" +
"e3da52abc8fbdb38b113a187ed0ac763fa86d1d4;seq3\n",
},
}
// Suppress the expected warning about empty sequences
oldLogOutput := log.Writer()
log.SetOutput(io.Discard)
defer log.SetOutput(oldLogOutput)
for _, tt := range tests {
t.Run(filepath.Base(tt.file), func(t *testing.T) {
setArgs(t, "seqhasher", "-n", "-o", tt.file)
var out bytes.Buffer
if err := run(&out); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got := out.String(); got != tt.expected {
t.Errorf("got:\n%s\nwant:\n%s", got, tt.expected)
}
})
}
}
func TestRun(t *testing.T) {
t.Run("Version flag", func(t *testing.T) {
setArgs(t, "seqhasher", "-version")
var out bytes.Buffer
if err := run(&out); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if want := fmt.Sprintf("SeqHasher %s\n", version); out.String() != want {
t.Errorf("got %q, want %q", out.String(), want)
}
})
t.Run("No input file prints usage", func(t *testing.T) {
setArgs(t, "seqhasher")
var out bytes.Buffer
if err := run(&out); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !strings.Contains(out.String(), "Usage:") {
t.Errorf("expected usage, got %q", out.String())
}
})
t.Run("Invalid hash type", func(t *testing.T) {
setArgs(t, "seqhasher", "-H", "sha256", testFastaPath)
if err := run(io.Discard); err == nil || !strings.Contains(err.Error(), "invalid hash type") {
t.Errorf("expected invalid hash type error, got %v", err)
}
})
t.Run("Non-existent input file", func(t *testing.T) {
setArgs(t, "seqhasher", filepath.Join(t.TempDir(), "nonexistent.fasta"))
err := run(io.Discard)
if !errors.Is(err, fs.ErrNotExist) || !strings.HasPrefix(err.Error(), "error opening input:") {
t.Errorf("expected wrapped fs.ErrNotExist, got %v", err)
}
})
t.Run("Valid input file", func(t *testing.T) {
setArgs(t, "seqhasher", testFastaPath)
var out bytes.Buffer
if err := run(&out); err != nil {
t.Fatalf("unexpected error: %v", err)
}
want := ">./test/test.fasta;65c89f59d38cdbf90dfaf0b0a6884829df8396b0;seq1\nACTG\n"
if !strings.HasPrefix(out.String(), want) {
t.Errorf("got %q, want prefix %q", out.String(), want)
}
})
t.Run("Output to file", func(t *testing.T) {
path := filepath.Join(t.TempDir(), "out.fasta")
setArgs(t, "seqhasher", "-n", testFastaPath, path)
var out bytes.Buffer
if err := run(&out); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if out.Len() != 0 {
t.Errorf("expected no output to writer, got %q", out.String())
}
content, err := os.ReadFile(path)
if err != nil {
t.Fatalf("failed to read output file: %v", err)
}
if !strings.HasPrefix(string(content), ">65c89f59d38cdbf90dfaf0b0a6884829df8396b0;seq1\nACTG\n") {
t.Errorf("unexpected output file content: %q", content)
}
})
t.Run("Output to invalid directory", func(t *testing.T) {
path := filepath.Join(t.TempDir(), "nonexistent", "out.fasta")
setArgs(t, "seqhasher", testFastaPath, path)
err := run(io.Discard)
if !errors.Is(err, fs.ErrNotExist) || !strings.HasPrefix(err.Error(), "error opening output:") {
t.Errorf("expected wrapped fs.ErrNotExist, got %v", err)
}
})
t.Run("Stdin to stdout", func(t *testing.T) {
setStdin(t, ">seq1\nactg\n")
setArgs(t, "seqhasher", "-H", "md5", "-", "-")
var out bytes.Buffer
if err := run(&out); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if want := ">86bfb9f78dd8b6cd35962bb7324fdbf8;seq1\nACTG\n"; out.String() != want {
t.Errorf("got %q, want %q", out.String(), want)
}
})
t.Run("Stdin FASTQ with name override", func(t *testing.T) {
setStdin(t, "@seq1\nACTG\n+\nIIII\n")
setArgs(t, "seqhasher", "--name", "sample", "-")
var out bytes.Buffer
if err := run(&out); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if want := "@sample;65c89f59d38cdbf90dfaf0b0a6884829df8396b0;seq1\nACTG\n+\nIIII\n"; out.String() != want {
t.Errorf("got %q, want %q", out.String(), want)
}
})
}
func TestPrintUsage(t *testing.T) {
t.Run("Regular usage", func(t *testing.T) {
setArgs(t, "seqhasher")
var buf bytes.Buffer
printUsage(&buf)
for _, str := range []string{
"SeqHasher v",
"Usage: seqhasher [options]",
"Options:",
"Supported hash types:",
"If input_file is '-' or omitted, reads from stdin",
} {
if !strings.Contains(buf.String(), str) {
t.Errorf("expected usage output to contain %q\ngot:\n%s", str, buf.String())
}
}
})
t.Run("Detailed help", func(t *testing.T) {
setArgs(t, "seqhasher", "--help")
var buf bytes.Buffer
printUsage(&buf)
for _, str := range []string{
"SeqHasher",
"DNA Sequence Hashing Tool",
"version:",
"Usage:",
"Overview:",
"Options:",
"Arguments:",
"Examples:",
"https://github.com/vmikk/seqhasher",
} {
if !strings.Contains(buf.String(), str) {
t.Errorf("expected detailed help to contain %q\ngot:\n%s", str, buf.String())
}
}
})
}
func TestFlagUsage(t *testing.T) {
// parseFlags sets flag.Usage, which is called on flag parsing errors and must print to stderr
setArgs(t, "seqhasher")
if _, err := parseFlags(); err != nil {
t.Fatalf("unexpected error: %v", err)
}
r, w, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
oldStderr := os.Stderr
os.Stderr = w
flag.Usage()
os.Stderr = oldStderr
_ = w.Close()
var buf bytes.Buffer
if _, err := io.Copy(&buf, r); err != nil {
t.Fatal(err)
}
_ = r.Close()
for _, str := range []string{"SeqHasher v", "Usage:", "Options:", "-hash", "Supported hash types:"} {
if !strings.Contains(buf.String(), str) {
t.Errorf("expected flag.Usage output to contain %q\ngot:\n%s", str, buf.String())
}
}
}