go-hep.org/x/hep@v0.38.1/cmd/root2npy/main_test.go (about) 1 // Copyright ©2020 The go-hep Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package main 6 7 import ( 8 "fmt" 9 "io" 10 "os" 11 "path/filepath" 12 "strings" 13 "testing" 14 15 "codeberg.org/sbinet/npyio" 16 "go-hep.org/x/hep/internal/diff" 17 ) 18 19 func TestProcess(t *testing.T) { 20 loadRef := func(fname string) string { 21 t.Helper() 22 raw, err := os.ReadFile(fname) 23 if err != nil { 24 t.Fatalf("could not load reference file %q: %+v", fname, err) 25 } 26 return string(raw) 27 } 28 29 tmp, err := os.MkdirTemp("", "root2npy-") 30 if err != nil { 31 t.Fatalf("could not create tmp dir: %+v", err) 32 } 33 defer os.RemoveAll(tmp) 34 35 for _, tc := range []struct { 36 name string 37 tree string 38 want string 39 }{ 40 { 41 name: "../../groot/testdata/simple.root", 42 tree: "tree", 43 want: loadRef("testdata/simple.root.txt"), 44 }, 45 { 46 name: "../../groot/testdata/leaves.root", 47 tree: "tree", 48 want: loadRef("testdata/leaves.root.txt"), 49 }, 50 { 51 name: "../../groot/testdata/ndim.root", 52 tree: "tree", 53 want: loadRef("testdata/ndim.root.txt"), 54 }, 55 { 56 name: "../../groot/testdata/small-flat-tree.root", 57 tree: "tree", 58 want: loadRef("testdata/small-flat-tree.root.txt"), 59 }, 60 } { 61 t.Run(tc.name, func(t *testing.T) { 62 oname := filepath.Join(tmp, filepath.Base(tc.name)+".npz") 63 err := process(oname, tc.name, tc.tree) 64 if err != nil { 65 t.Fatalf("could not run root2npy: %+v", err) 66 } 67 68 f, err := os.Open(oname) 69 if err != nil { 70 t.Fatalf("could not open %q: %+v", oname, err) 71 } 72 defer f.Close() 73 74 type namer interface{ Name() string } 75 76 r := struct { 77 io.ReaderAt 78 io.Seeker 79 namer 80 }{ 81 ReaderAt: f, 82 Seeker: f, 83 namer: nilNamer{}, 84 } 85 86 var got strings.Builder 87 err = npyio.Dump(&got, r) 88 if err != nil { 89 t.Fatalf("could not read output file: %+v", err) 90 } 91 92 if got, want := got.String(), tc.want; got != want { 93 t.Fatalf("invalid npy:\ngot:\n%s\nwant:\n%s\ndiff:\n%s", got, want, diff.Format(got, want)) 94 } 95 }) 96 } 97 } 98 99 type nilNamer struct{} 100 101 func (nilNamer) Name() string { return "output.npz" } 102 103 func BenchmarkProcess(b *testing.B) { 104 tmp, err := os.MkdirTemp("", "root2npy-") 105 if err != nil { 106 b.Fatalf("could not create tmp dir: %+v", err) 107 } 108 defer os.RemoveAll(tmp) 109 110 const ( 111 fname = "../../groot/testdata/small-flat-tree.root" 112 tname = "tree" 113 ) 114 itr := 0 115 b.ReportAllocs() 116 b.ResetTimer() 117 for i := 0; i < b.N; i++ { 118 b.StopTimer() 119 oname := filepath.Join(tmp, fmt.Sprintf("o-%d.npz", itr)) 120 itr++ 121 b.StartTimer() 122 err := process(oname, fname, tname) 123 if err != nil { 124 b.Fatal(err) 125 } 126 } 127 }