Skip to content

Instantly share code, notes, and snippets.

@jnovikov
Created August 21, 2019 20:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jnovikov/713212fc88ea588ff2bf5c5228256564 to your computer and use it in GitHub Desktop.
Save jnovikov/713212fc88ea588ff2bf5c5228256564 to your computer and use it in GitHub Desktop.
Golang standart library test example
package power
import "errors"
var NegativeError = errors.New("Negative component is not supported")
func power(base, i int) int {
if i == 0 {
return 1
}
if i % 2 == 0 {
tmp := power(base, i / 2)
return tmp * tmp
} else {
return base * power(base, i - 1)
}
}
func Power(base, exponent int) (int, error) {
if exponent < 0 {
return -1, NegativeError
}
return power(base, exponent), nil
}
package power
import "testing"
func TestPower(t *testing.T) {
for _, tc := range []struct{
message string
base int
exponent int
result int
error error
}{
{"Positive base and exp", 2, 10,1024, nil},
{"n^1 == n", 2, 1, 2, nil},
{"n^0 == 1", 2,0,1,nil},
{"Negative base", -2, 3, -8, nil},
{"Negative exponent", 2, -1, -1, NegativeError},
} {
r, err := Power(tc.base, tc.exponent)
if err != tc.error {
t.Errorf("%s test failed. Expected error: %s; Actual: %s", tc.message, tc.error, err)
}
if r != tc.result {
t.Errorf("%s test failed. Expected: %d; Actual: %d", tc.message, tc.result, r)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment