test: improve testing quality

main
Jef Roosens 2022-12-28 17:39:20 +01:00 committed by Chewing_Bever
parent 7e9af5c6c8
commit 44aa7c9dc9
Signed by: Jef Roosens
GPG Key ID: B75D4F293C7052DB
4 changed files with 60 additions and 4 deletions

28
conf.v
View File

@ -2,6 +2,7 @@ module conf
import os
import toml
import datatypes { Set }
// get_env_var tries to read the contents of the given environment variable. It
// looks for either `${env.prefix}${field_name.to_upper()}` or
@ -54,7 +55,7 @@ pub fn load<T>(conf LoadConfig) !T {
// This array allows us to determine later whether the variable is actually
// zero or just a null'ed struct field
mut has_value := map[string]bool{}
mut has_value := Set<string>{}
// Later, this could be read from an env var as well.
path := conf.default_path
@ -77,7 +78,7 @@ pub fn load<T>(conf LoadConfig) !T {
// $compile_error('Unsupported config struct field type detected.')
}
has_value[field.name] = true
has_value.add(field.name)
}
}
}
@ -97,12 +98,31 @@ pub fn load<T>(conf LoadConfig) !T {
// $compile_error('Unsupported config struct field type detected.')
}
has_value[field.name] = true
has_value.add(field.name)
}
if !(has_value[field.name] or { false }) {
// Finally, if there's no env var present either, we check whether the
// variable has a default value
if !has_value.exists(field.name) {
mut has_default := false
$if field.typ is string {
has_default = res.$(field.name) != ''
} $else $if field.typ is int {
has_default = res.$(field.name) != 0
}
if has_default {
has_value.add(field.name)
}
}
// If there's no value provided in any way, we notify the user with an
// error.
if !has_value.exists(field.name) {
return error("Missing config variable '$field.name' with no provided default. Either add it to the config file or provide it using an environment variable.")
}
}
return res
}

35
string_test.v 100644
View File

@ -0,0 +1,35 @@
module conf
struct SingleConf {
some_string string
}
struct SingleConfDefault {
some_string string = 'default'
}
fn test_string_present_no_default() {
conf := load<SingleConf>(default_path: 'test/string.toml')!
assert conf == SingleConf{
some_string: 'hi'
}
}
fn test_string_absent_no_default() {
conf := load<SingleConf>(default_path: 'test/empty.toml') or { return }
assert false
}
fn test_string_present_default() {
conf := load<SingleConfDefault>(default_path: 'test/string.toml')!
assert conf == SingleConfDefault{
some_string: 'hi'
}
}
fn test_string_absent_default() {
conf := load<SingleConfDefault>(default_path: 'test/empty.toml')!
assert conf == SingleConfDefault{
some_string: 'default'
}
}

0
test/empty.toml 100644
View File

1
test/string.toml 100644
View File

@ -0,0 +1 @@
some_string = "hi"