mirror of
https://github.com/ipfs/kubo.git
synced 2026-02-24 11:57:44 +08:00
This commit replaces `os.MkdirTemp` with `t.TempDir` in tests. The
directory created by `t.TempDir` is automatically removed when the test
and all its subtests complete.
Prior to this commit, temporary directory created using `os.MkdirTemp`
needs to be removed manually by calling `os.RemoveAll`, which is omitted
in some tests. The error handling boilerplate e.g.
defer func() {
if err := os.RemoveAll(dir); err != nil {
t.Fatal(err)
}
}
is also tedious, but `t.TempDir` handles this for us nicely.
Reference: https://pkg.go.dev/testing#T.TempDir
Signed-off-by: Eng Zer Jun <engzerjun@gmail.com>
79 lines
1.5 KiB
Go
79 lines
1.5 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"log"
|
|
"os"
|
|
"os/exec"
|
|
"path"
|
|
"testing"
|
|
|
|
"github.com/ipfs/kubo/thirdparty/unit"
|
|
|
|
config "github.com/ipfs/kubo/config"
|
|
random "github.com/jbenet/go-random"
|
|
)
|
|
|
|
func main() {
|
|
if err := compareResults(); err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
}
|
|
|
|
func compareResults() error {
|
|
var amount unit.Information
|
|
for amount = 10 * unit.MB; amount > 0; amount = amount * 2 {
|
|
if results, err := benchmarkAdd(int64(amount)); err != nil { // TODO compare
|
|
return err
|
|
} else {
|
|
log.Println(amount, "\t", results)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func benchmarkAdd(amount int64) (*testing.BenchmarkResult, error) {
|
|
results := testing.Benchmark(func(b *testing.B) {
|
|
b.SetBytes(amount)
|
|
for i := 0; i < b.N; i++ {
|
|
b.StopTimer()
|
|
tmpDir := b.TempDir()
|
|
|
|
env := append(os.Environ(), fmt.Sprintf("%s=%s", config.EnvDir, path.Join(tmpDir, config.DefaultPathName)))
|
|
setupCmd := func(cmd *exec.Cmd) {
|
|
cmd.Env = env
|
|
}
|
|
|
|
cmd := exec.Command("ipfs", "init", "-b=2048")
|
|
setupCmd(cmd)
|
|
if err := cmd.Run(); err != nil {
|
|
b.Fatal(err)
|
|
}
|
|
|
|
const seed = 1
|
|
f, err := os.CreateTemp("", "")
|
|
if err != nil {
|
|
b.Fatal(err)
|
|
}
|
|
defer os.Remove(f.Name())
|
|
|
|
err = random.WritePseudoRandomBytes(amount, f, seed)
|
|
if err != nil {
|
|
b.Fatal(err)
|
|
}
|
|
if err := f.Close(); err != nil {
|
|
b.Fatal(err)
|
|
}
|
|
|
|
b.StartTimer()
|
|
cmd = exec.Command("ipfs", "add", f.Name())
|
|
setupCmd(cmd)
|
|
if err := cmd.Run(); err != nil {
|
|
b.Fatal(err)
|
|
}
|
|
b.StopTimer()
|
|
}
|
|
})
|
|
return &results, nil
|
|
}
|