refactor(tests): remove `TmpFile.Error` to centralize error checks

This commit is contained in:
ThinkChaos 2023-11-24 12:31:51 -05:00
parent 891d0fba74
commit 8c7b89cbb3
14 changed files with 49 additions and 159 deletions

View File

@ -80,7 +80,7 @@ linters-settings:
stylecheck: stylecheck:
# Whietlist dot imports for test packages. # Whietlist dot imports for test packages.
dot-import-whitelist: dot-import-whitelist:
- "github.com/onsi/ginkgo" - "github.com/onsi/ginkgo/v2"
- "github.com/onsi/gomega" - "github.com/onsi/gomega"
- "github.com/0xERR0R/blocky/config/migration" - "github.com/0xERR0R/blocky/config/migration"
- "github.com/0xERR0R/blocky/helpertest" - "github.com/0xERR0R/blocky/helpertest"

View File

@ -33,8 +33,6 @@ var _ = Describe("root command", func() {
configPath = defaultConfigPath configPath = defaultConfigPath
tmpDir = NewTmpFolder("RootCommand") tmpDir = NewTmpFolder("RootCommand")
Expect(tmpDir.Error).Should(Succeed())
tmpFile = tmpDir.CreateStringFile("config", tmpFile = tmpDir.CreateStringFile("config",
"upstreams:", "upstreams:",
" groups:", " groups:",
@ -49,7 +47,6 @@ var _ = Describe("root command", func() {
" - ads", " - ads",
"port: 5333", "port: 5333",
) )
Expect(tmpFile.Error).Should(Succeed())
}) })
It("should accept old env var", func() { It("should accept old env var", func() {

View File

@ -24,7 +24,7 @@ var _ = Describe("Serve command", func() {
BeforeEach(func() { BeforeEach(func() {
port = helpertest.GetStringPort(basePort) port = helpertest.GetStringPort(basePort)
tmpDir = helpertest.NewTmpFolder("config") tmpDir = helpertest.NewTmpFolder("config")
Expect(tmpDir.Error).Should(Succeed())
configPath = defaultConfigPath configPath = defaultConfigPath
}) })
@ -38,9 +38,10 @@ var _ = Describe("Serve command", func() {
" - 1.1.1.1", " - 1.1.1.1",
"ports:", "ports:",
" dns: "+port) " dns: "+port)
Expect(cfgFile.Error).Should(Succeed())
os.Setenv(configFileEnvVar, cfgFile.Path) os.Setenv(configFileEnvVar, cfgFile.Path)
DeferCleanup(func() { os.Unsetenv(configFileEnvVar) }) DeferCleanup(func() { os.Unsetenv(configFileEnvVar) })
initConfig() initConfig()
}) })
@ -84,9 +85,10 @@ var _ = Describe("Serve command", func() {
" - 1.1.1.1", " - 1.1.1.1",
"ports:", "ports:",
" dns: "+port) " dns: "+port)
Expect(cfgFile.Error).Should(Succeed())
os.Setenv(configFileEnvVar, cfgFile.Path) os.Setenv(configFileEnvVar, cfgFile.Path)
DeferCleanup(func() { os.Unsetenv(configFileEnvVar) }) DeferCleanup(func() { os.Unsetenv(configFileEnvVar) })
initConfig() initConfig()
}) })

View File

@ -30,7 +30,6 @@ var _ = Describe("Config", func() {
BeforeEach(func() { BeforeEach(func() {
tmpDir = helpertest.NewTmpFolder("config") tmpDir = helpertest.NewTmpFolder("config")
Expect(tmpDir.Error).Should(Succeed())
}) })
Describe("Deprecated parameters are converted", func() { Describe("Deprecated parameters are converted", func() {
@ -147,14 +146,9 @@ var _ = Describe("Config", func() {
Describe("Creation of Config", func() { Describe("Creation of Config", func() {
When("Test config file will be parsed", func() { When("Test config file will be parsed", func() {
var confFile *helpertest.TmpFile
BeforeEach(func() {
confFile = writeConfigYml(tmpDir)
Expect(confFile.Error).Should(Succeed())
})
It("should return a valid config struct", func() { It("should return a valid config struct", func() {
confFile := writeConfigYml(tmpDir)
c, err = LoadConfig(confFile.Path, true) c, err = LoadConfig(confFile.Path, true)
Expect(err).Should(Succeed()) Expect(err).Should(Succeed())
@ -169,8 +163,7 @@ var _ = Describe("Config", func() {
}) })
When("Multiple config files are used", func() { When("Multiple config files are used", func() {
BeforeEach(func() { BeforeEach(func() {
err = writeConfigDir(tmpDir) writeConfigDir(tmpDir)
Expect(err).Should(Succeed())
}) })
It("should return a valid config struct", func() { It("should return a valid config struct", func() {
@ -204,7 +197,6 @@ var _ = Describe("Config", func() {
When("config file is malformed", func() { When("config file is malformed", func() {
It("should return error", func() { It("should return error", func() {
cfgFile := tmpDir.CreateStringFile("config.yml", "malformed_config") cfgFile := tmpDir.CreateStringFile("config.yml", "malformed_config")
Expect(cfgFile.Error).Should(Succeed())
c, err = LoadConfig(cfgFile.Path, true) c, err = LoadConfig(cfgFile.Path, true)
Expect(err).Should(HaveOccurred()) Expect(err).Should(HaveOccurred())
@ -865,8 +857,8 @@ func writeConfigYml(tmpDir *helpertest.TmpFolder) *helpertest.TmpFile {
) )
} }
func writeConfigDir(tmpDir *helpertest.TmpFolder) error { func writeConfigDir(tmpDir *helpertest.TmpFolder) {
f1 := tmpDir.CreateStringFile("config1.yaml", tmpDir.CreateStringFile("config1.yaml",
"upstreams:", "upstreams:",
" startVerify: false", " startVerify: false",
" userAgent: testBlocky", " userAgent: testBlocky",
@ -888,11 +880,8 @@ func writeConfigDir(tmpDir *helpertest.TmpFolder) error {
" - AAAA", " - AAAA",
" - A", " - A",
) )
if f1.Error != nil {
return f1.Error
}
f2 := tmpDir.CreateStringFile("config2.yaml", tmpDir.CreateStringFile("config2.yaml",
"blocking:", "blocking:",
" blackLists:", " blackLists:",
" ads:", " ads:",
@ -930,8 +919,6 @@ func writeConfigDir(tmpDir *helpertest.TmpFolder) error {
"logLevel: debug", "logLevel: debug",
"minTlsServeVersion: 1.3", "minTlsServeVersion: 1.3",
) )
return f2.Error
} }
// Tiny helper to get a new pointer with a value. // Tiny helper to get a new pointer with a value.

View File

@ -79,9 +79,6 @@ func createHTTPServerContainer(ctx context.Context, alias string, tmpDir *helper
f1 := tmpDir.CreateStringFile(filename, f1 := tmpDir.CreateStringFile(filename,
lines..., lines...,
) )
if f1.Error != nil {
return nil, f1.Error
}
const modeOwner = 700 const modeOwner = 700
@ -160,9 +157,6 @@ func createBlockyContainer(ctx context.Context, tmpDir *helpertest.TmpFolder,
f1 := tmpDir.CreateStringFile("config1.yaml", f1 := tmpDir.CreateStringFile("config1.yaml",
lines..., lines...,
) )
if f1.Error != nil {
return nil, f1.Error
}
cfg, err := config.LoadConfig(f1.Path, true) cfg, err := config.LoadConfig(f1.Path, true)
if err != nil { if err != nil {

View File

@ -53,7 +53,6 @@ var _ = BeforeSuite(func(ctx context.Context) {
}) })
tmpDir = helpertest.NewTmpFolder("config") tmpDir = helpertest.NewTmpFolder("config")
Expect(tmpDir.Error).Should(Succeed())
SetDefaultEventuallyTimeout(5 * time.Second) SetDefaultEventuallyTimeout(5 * time.Second)
}) })

View File

@ -6,18 +6,17 @@ import (
"os" "os"
"path/filepath" "path/filepath"
"github.com/onsi/ginkgo/v2" . "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
) )
type TmpFolder struct { type TmpFolder struct {
Path string Path string
Error error
prefix string prefix string
} }
type TmpFile struct { type TmpFile struct {
Path string Path string
Error error
Folder *TmpFolder Folder *TmpFolder
} }
@ -29,14 +28,14 @@ func NewTmpFolder(prefix string) *TmpFolder {
} }
path, err := os.MkdirTemp("", ipref) path, err := os.MkdirTemp("", ipref)
Expect(err).Should(Succeed())
res := &TmpFolder{ res := &TmpFolder{
Path: path, Path: path,
Error: err,
prefix: ipref, prefix: ipref,
} }
ginkgo.DeferCleanup(res.Clean) DeferCleanup(res.Clean)
return res return res
} }
@ -61,9 +60,10 @@ func (tf *TmpFolder) CreateSubFolder(name string) *TmpFolder {
path, err = os.MkdirTemp(tf.Path, tf.prefix) path, err = os.MkdirTemp(tf.Path, tf.prefix)
} }
Expect(err).Should(Succeed())
res := &TmpFolder{ res := &TmpFolder{
Path: path, Path: path,
Error: err,
prefix: tf.prefix, prefix: tf.prefix,
} }
@ -71,100 +71,63 @@ func (tf *TmpFolder) CreateSubFolder(name string) *TmpFolder {
} }
func (tf *TmpFolder) CreateEmptyFile(name string) *TmpFile { func (tf *TmpFolder) CreateEmptyFile(name string) *TmpFile {
f, err := tf.createFile(name) f, res := tf.createFile(name)
if err != nil { defer f.Close()
return tf.newErrorTmpFile(err)
}
return tf.checkState(f, err) return res
} }
func (tf *TmpFolder) CreateStringFile(name string, lines ...string) *TmpFile { func (tf *TmpFolder) CreateStringFile(name string, lines ...string) *TmpFile {
f, err := tf.createFile(name) f, res := tf.createFile(name)
if err != nil { defer f.Close()
return tf.newErrorTmpFile(err)
}
first := true first := true
w := bufio.NewWriter(f) w := bufio.NewWriter(f)
for _, l := range lines { for _, l := range lines {
if first { if first {
first = false first = false
} else { } else {
_, err = w.WriteString("\n") _, err := w.WriteString("\n")
Expect(err).Should(Succeed())
} }
if err != nil { _, err := w.WriteString(l)
break Expect(err).Should(Succeed())
}
_, err = w.WriteString(l)
if err != nil {
break
}
} }
w.Flush() w.Flush()
return tf.checkState(f, err) return res
} }
func (tf *TmpFolder) JoinPath(name string) string { func (tf *TmpFolder) JoinPath(name string) string {
return filepath.Join(tf.Path, name) return filepath.Join(tf.Path, name)
} }
func (tf *TmpFolder) CountFiles() (int, error) { func (tf *TmpFolder) ReadDir() []fs.DirEntry {
files, err := os.ReadDir(tf.Path) files, err := os.ReadDir(tf.Path)
if err != nil { Expect(err).Should(Succeed())
return 0, err
}
return len(files), nil return files
} }
func (tf *TmpFolder) createFile(name string) (*os.File, error) { func (tf *TmpFolder) createFile(name string) (*os.File, *TmpFile) {
var (
f *os.File
err error
)
if len(name) > 0 { if len(name) > 0 {
return os.Create(filepath.Join(tf.Path, name)) f, err = os.Create(filepath.Join(tf.Path, name))
} else {
f, err = os.CreateTemp(tf.Path, "temp")
} }
return os.CreateTemp(tf.Path, "temp") Expect(err).Should(Succeed())
}
func (tf *TmpFolder) newErrorTmpFile(err error) *TmpFile { return f, &TmpFile{
return &TmpFile{ Path: f.Name(),
Path: "",
Error: err,
Folder: tf, Folder: tf,
} }
} }
func (tf *TmpFolder) checkState(file *os.File, ierr error) *TmpFile {
err := ierr
filepath := ""
if file != nil {
filepath = file.Name()
file.Close()
_, err = os.Stat(filepath)
}
return &TmpFile{
Path: filepath,
Error: err,
Folder: tf,
}
}
func (tf *TmpFile) Stat() error {
if tf.Error != nil {
return tf.Error
}
_, res := os.Stat(tf.Path)
return res
}

View File

@ -61,20 +61,13 @@ var _ = Describe("ListCache", func() {
server3 = TestServer("blocked3.com\nblocked1a.com") server3 = TestServer("blocked3.com\nblocked1a.com")
tmpDir = NewTmpFolder("ListCache") tmpDir = NewTmpFolder("ListCache")
Expect(tmpDir.Error).Should(Succeed())
DeferCleanup(tmpDir.Clean) DeferCleanup(tmpDir.Clean)
emptyFile = tmpDir.CreateStringFile("empty", "#empty file") emptyFile = tmpDir.CreateStringFile("empty", "#empty file")
Expect(emptyFile.Error).Should(Succeed())
emptyFile = tmpDir.CreateStringFile("empty", "#empty file") emptyFile = tmpDir.CreateStringFile("empty", "#empty file")
Expect(emptyFile.Error).Should(Succeed())
file1 = tmpDir.CreateStringFile("file1", "blocked1.com", "blocked1a.com") file1 = tmpDir.CreateStringFile("file1", "blocked1.com", "blocked1a.com")
Expect(file1.Error).Should(Succeed())
file2 = tmpDir.CreateStringFile("file2", "blocked2.com") file2 = tmpDir.CreateStringFile("file2", "blocked2.com")
Expect(file2.Error).Should(Succeed())
file3 = tmpDir.CreateStringFile("file3", "blocked3.com", "blocked1a.com") file3 = tmpDir.CreateStringFile("file3", "blocked3.com", "blocked1a.com")
Expect(file3.Error).Should(Succeed())
}) })
JustBeforeEach(func() { JustBeforeEach(func() {

View File

@ -25,7 +25,6 @@ var _ = Describe("FileWriter", func() {
JustBeforeEach(func() { JustBeforeEach(func() {
tmpDir = helpertest.NewTmpFolder("fileWriter") tmpDir = helpertest.NewTmpFolder("fileWriter")
Expect(tmpDir.Error).Should(Succeed())
}) })
Describe("CSV writer", func() { Describe("CSV writer", func() {
@ -116,21 +115,11 @@ var _ = Describe("FileWriter", func() {
}) })
}) })
Eventually(func(g Gomega) int { Expect(tmpDir.ReadDir()).Should(HaveLen(2))
filesCount, err := tmpDir.CountFiles()
g.Expect(err).Should(Succeed())
return filesCount writer.CleanUp()
}, "20s", "1s").Should(Equal(2))
go writer.CleanUp() Expect(tmpDir.ReadDir()).Should(HaveLen(1))
Eventually(func(g Gomega) int {
filesCount, err := tmpDir.CountFiles()
g.Expect(err).Should(Succeed())
return filesCount
}, "20s", "1s").Should(Equal(1))
}) })
}) })
}) })

View File

@ -28,20 +28,13 @@ var (
var _ = BeforeSuite(func() { var _ = BeforeSuite(func() {
tmpDir = NewTmpFolder("BlockingResolver") tmpDir = NewTmpFolder("BlockingResolver")
Expect(tmpDir.Error).Should(Succeed())
group1File = tmpDir.CreateStringFile("group1File", "DOMAIN1.com") group1File = tmpDir.CreateStringFile("group1File", "DOMAIN1.com")
Expect(group1File.Error).Should(Succeed())
group2File = tmpDir.CreateStringFile("group2File", "blocked2.com") group2File = tmpDir.CreateStringFile("group2File", "blocked2.com")
Expect(group2File.Error).Should(Succeed())
defaultGroupFile = tmpDir.CreateStringFile("defaultGroupFile", defaultGroupFile = tmpDir.CreateStringFile("defaultGroupFile",
"blocked3.com", "blocked3.com",
"123.145.123.145", "123.145.123.145",
"2001:db8:85a3:08d3::370:7344", "2001:db8:85a3:08d3::370:7344",
"badcnamedomain.com") "badcnamedomain.com")
Expect(defaultGroupFile.Error).Should(Succeed())
}) })
var _ = Describe("BlockingResolver", Label("blockingResolver"), func() { var _ = Describe("BlockingResolver", Label("blockingResolver"), func() {

View File

@ -41,10 +41,7 @@ var _ = Describe("HostsFileResolver", func() {
DeferCleanup(cancelFn) DeferCleanup(cancelFn)
tmpDir = NewTmpFolder("HostsFileResolver") tmpDir = NewTmpFolder("HostsFileResolver")
Expect(tmpDir.Error).Should(Succeed())
tmpFile = writeHostFile(tmpDir) tmpFile = writeHostFile(tmpDir)
Expect(tmpFile.Error).Should(Succeed())
sutConfig = config.HostsFileConfig{ sutConfig = config.HostsFileConfig{
Sources: config.NewBytesSources(tmpFile.Path), Sources: config.NewBytesSources(tmpFile.Path),
@ -164,7 +161,6 @@ var _ = Describe("HostsFileResolver", func() {
"127.0.0.x localhost", "127.0.0.x localhost",
"256.0.0.1 localhost", "256.0.0.1 localhost",
) )
Expect(tmpFile.Error).Should(Succeed())
sutConfig.Sources = config.NewBytesSources(tmpFile.Path) sutConfig.Sources = config.NewBytesSources(tmpFile.Path)
}) })

View File

@ -61,7 +61,6 @@ var _ = Describe("QueryLoggingResolver", func() {
mockAnswer = new(dns.Msg) mockAnswer = new(dns.Msg)
tmpDir = NewTmpFolder("queryLoggingResolver") tmpDir = NewTmpFolder("queryLoggingResolver")
Expect(tmpDir.Error).Should(Succeed())
}) })
JustBeforeEach(func() { JustBeforeEach(func() {
@ -338,21 +337,13 @@ var _ = Describe("QueryLoggingResolver", func() {
dateBefore9Days := time.Now().AddDate(0, 0, -9) dateBefore9Days := time.Now().AddDate(0, 0, -9)
f1 := tmpDir.CreateEmptyFile(fmt.Sprintf("%s-test.log", dateBefore7Days.Format("2006-01-02"))) f1 := tmpDir.CreateEmptyFile(fmt.Sprintf("%s-test.log", dateBefore7Days.Format("2006-01-02")))
Expect(f1.Error).Should(Succeed())
f2 := tmpDir.CreateEmptyFile(fmt.Sprintf("%s-test.log", dateBefore9Days.Format("2006-01-02"))) f2 := tmpDir.CreateEmptyFile(fmt.Sprintf("%s-test.log", dateBefore9Days.Format("2006-01-02")))
Expect(f2.Error).Should(Succeed())
sut.doCleanUp() sut.doCleanUp()
Eventually(func(g Gomega) { Eventually(func(g Gomega) {
// file 1 exist g.Expect(f1.Path).Should(BeAnExistingFile())
g.Expect(f1.Stat()).Should(Succeed()) g.Expect(f2.Path).ShouldNot(BeAnExistingFile())
// file 2 was deleted
ierr2 := f2.Stat()
g.Expect(ierr2).Should(HaveOccurred())
g.Expect(os.IsNotExist(ierr2)).Should(BeTrue())
}).Should(Succeed()) }).Should(Succeed())
}) })
}) })

View File

@ -93,25 +93,12 @@ var _ = BeforeSuite(func() {
upstreamGoogle = googleMockUpstream.Start() upstreamGoogle = googleMockUpstream.Start()
tmpDir := NewTmpFolder("server") tmpDir := NewTmpFolder("server")
Expect(tmpDir.Error).Should(Succeed())
certPem := writeCertPem(tmpDir) certPem := writeCertPem(tmpDir)
Expect(certPem.Error).Should(Succeed())
keyPem := writeKeyPem(tmpDir) keyPem := writeKeyPem(tmpDir)
Expect(keyPem.Error).Should(Succeed())
doubleclickFile := tmpDir.CreateStringFile("doubleclick.net.txt", "doubleclick.net", "doubleclick.net.cn") doubleclickFile := tmpDir.CreateStringFile("doubleclick.net.txt", "doubleclick.net", "doubleclick.net.cn")
Expect(doubleclickFile.Error).Should(Succeed())
bildFile := tmpDir.CreateStringFile("www.bild.de.txt", "www.bild.de") bildFile := tmpDir.CreateStringFile("www.bild.de.txt", "www.bild.de")
Expect(bildFile.Error).Should(Succeed())
heiseFile := tmpDir.CreateStringFile("heise.de.txt", "heise.de") heiseFile := tmpDir.CreateStringFile("heise.de.txt", "heise.de")
Expect(heiseFile.Error).Should(Succeed())
youtubeFile := tmpDir.CreateStringFile("youtube.com.txt", "youtube.com") youtubeFile := tmpDir.CreateStringFile("youtube.com.txt", "youtube.com")
Expect(youtubeFile.Error).Should(Succeed())
cfg := &config.Config{ cfg := &config.Config{
CustomDNS: config.CustomDNS{ CustomDNS: config.CustomDNS{

View File

@ -15,12 +15,11 @@ var _ = Describe("Hostname function tests", func() {
BeforeEach(func() { BeforeEach(func() {
tmpDir = helpertest.NewTmpFolder("hostname") tmpDir = helpertest.NewTmpFolder("hostname")
Expect(tmpDir.Error).Should(Succeed())
}) })
It("should be used", func() { It("should be used", func() {
tmpFile := tmpDir.CreateStringFile("filetest1", "TestName ") tmpFile := tmpDir.CreateStringFile("filetest1", "TestName ")
Expect(tmpFile.Error).Should(Succeed())
getHostname(tmpFile.Path) getHostname(tmpFile.Path)
fhn, err := os.ReadFile(tmpFile.Path) fhn, err := os.ReadFile(tmpFile.Path)