Skip to content

Instantly share code, notes, and snippets.

@ankur22
Last active April 10, 2020 18:33
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 ankur22/860bc5f87be6385b853dc712501a73c3 to your computer and use it in GitHub Desktop.
Save ankur22/860bc5f87be6385b853dc712501a73c3 to your computer and use it in GitHub Desktop.
TDD and Golang
// Step 1: Write a failing test
func TestURLShortner(t *testing.T) {
var tests = []struct {
name, in, expected string
err error
}{
{"NoScheme", "https://google.com", "1", nil},
{"NoScheme", "google", "", errors.New("invalid")},
}
for _, test := range tests {
t.Run("Shorten"+test.name, func(t *testing.T) {
s := &URLShortner{i: 0, store: make(map[string]string)}
})
}
}
// Step 2: Write implementation code to get the tests to pass
type URLShortner struct {
store map[string]string
i int
}
// Step 3: Write test code to test the behaviour
func TestURLShortner(t *testing.T) {
var tests = []struct {
name, in, expected string
err error
}{
{"NoScheme", "https://google.com", "1", nil},
{"NoScheme", "google", "", errors.New("invalid")},
}
for _, test := range tests {
t.Run("Shorten"+test.name, func(t *testing.T) {
s := &URLShortner{i: 0, store: make(map[string]string)}
resp, err := s.Shorten(test.in)
assert.Equal(t, test.err, err)
assert.Equal(t, test.expected, resp)
})
}
}
// Step 4: Write the implementaton to get the tests to pass
func (u *URLShortner) Shorten(in string) (string, error) {
if !strings.Contains(in, ".com") {
return "", errors.New("invalid")
}
if !strings.Contains(in, "https://") {
in = fmt.Sprintf("https://%s", in)
}
u.i++
val := strconv.Itoa(u.i)
u.store[val] = in
return val, nil
}
// Step 5: Refactor the code and make sure that the tests still pass.
// Use code coverage tools to ensure that no new behaviour was added.
func (u *URLShortner) Shorten(in string) (string, error) {
_, err := url.ParseRequestURI(in)
if err != nil {
return "", errors.New("invalid")
}
if !strings.Contains(in, ".") {
return "", errors.New("invalid")
}
u.i++
val := strconv.Itoa(u.i)
u.store[val] = in
return val, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment