Skip to content

Commit

Permalink
Add error check linter; Check all errors
Browse files Browse the repository at this point in the history
  • Loading branch information
harveysanders committed Jan 2, 2023
1 parent c1321c6 commit f081812
Show file tree
Hide file tree
Showing 12 changed files with 152 additions and 77 deletions.
39 changes: 39 additions & 0 deletions .github/workflows/golangci-lint.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
name: golangci-lint
on: [push]
permissions:
contents: read
# Optional: allow read access to pull request. Use with `only-new-issues` option.
# pull-requests: read
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/setup-go@v3
with:
go-version: 1.18
- name: Checkout
uses: actions/checkout@v3
- name: Run linters
uses: golangci/golangci-lint-action@v3
with:
# Optional: version of golangci-lint to use in form of v1.2 or v1.2.3 or `latest` to use the latest version
version: latest

# Optional: working directory, useful for monorepos
# working-directory: somedir

# Optional: golangci-lint command line arguments.
# args: --issues-exit-code=0

# Optional: show only new issues if it's a pull request. The default value is `false`.
# only-new-issues: true

# Optional: if set to true then the all caching functionality will be complete disabled,
# takes precedence over all other caching options.
# skip-cache: true

# Optional: if set to true then the action don't cache or restore ~/go/pkg.
# skip-pkg-cache: true

# Optional: if set to true then the action don't cache or restore ~/.cache/go-build.
# skip-build-cache: true
4 changes: 3 additions & 1 deletion errors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,5 +94,7 @@ Response:
func JSONError(w http.ResponseWriter, err interface{}, code int) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(code)
json.NewEncoder(w).Encode(err)
if err := json.NewEncoder(w).Encode(err); err != nil {
panic(err)
}
}
6 changes: 4 additions & 2 deletions greenlight_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,15 @@ func TestPostWebhook(t *testing.T) {
// POSTs correct JSON body
var glReq Signup
d := json.NewDecoder(r.Body)
d.Decode(&glReq)
err := d.Decode(&glReq)
assertNilError(t, err)

assertDeepEqual(t, glReq, su)
}))

glSvc := NewGreenlightService(mockGreenlightSvr.URL, apiKey)

glSvc.postWebhook(context.Background(), su)
err := glSvc.postWebhook(context.Background(), su)
assertNilError(t, err)
})
}
32 changes: 19 additions & 13 deletions mailgun_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ func TestSendWelcome(t *testing.T) {
}

mockMailgunAPI := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.ParseMultipartForm(128)

err := r.ParseMultipartForm(128)
assertNilError(t, err)
// Check template version is not set
assertEqual(t, r.FormValue("t:version"), "")

Expand All @@ -56,7 +56,8 @@ func TestSendWelcome(t *testing.T) {
// Check the template variables are correct
jsonVars := r.Form.Get("h:X-Mailgun-Variables")
var gotVars welcomeVariables
json.Unmarshal([]byte(jsonVars), &gotVars)
err = json.Unmarshal([]byte(jsonVars), &gotVars)
assertNilError(t, err)

assertEqual(t, gotVars.FirstName, form.NameFirst)
assertEqual(t, gotVars.LastName, form.NameLast)
Expand All @@ -65,7 +66,8 @@ func TestSendWelcome(t *testing.T) {
// TODO: ZoomURL
// assertEqual(t, gotVars.ZoomURL, "TODO")

w.Write([]byte("{}"))
_, err = w.Write([]byte("{}"))
assertNilError(t, err)
}))
defer mockMailgunAPI.Close()

Expand All @@ -82,11 +84,14 @@ func TestSendWelcome(t *testing.T) {
os.Setenv("APP_ENV", "staging")

mockMailgunAPI := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.ParseMultipartForm(128)
err := r.ParseMultipartForm(128)
assertNilError(t, err)

assertEqual(t, r.FormValue("t:version"), "dev")

w.Write([]byte("{}"))
_, err = w.Write([]byte("{}"))
assertNilError(t, err)

}))

mgSvc := NewMailgunService(
Expand All @@ -96,10 +101,7 @@ func TestSendWelcome(t *testing.T) {
)

err := mgSvc.sendWelcome(context.Background(), Signup{})
if err != nil {
t.Fatal(err)
}

assertNilError(t, err)
})

t.Run("uses the 'info-session-signup-hybrid' template when 'hybrid' is true", func(t *testing.T) {
Expand All @@ -122,20 +124,24 @@ func TestSendWelcome(t *testing.T) {
}

mockMailgunAPI := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.ParseMultipartForm(128)
err := r.ParseMultipartForm(128)
assertNilError(t, err)

assertEqual(t, r.FormValue("template"), "info-session-signup-hybrid")

// Check the template variables are correct
jsonVars := r.Form.Get("h:X-Mailgun-Variables")
var gotVars welcomeVariables
json.Unmarshal([]byte(jsonVars), &gotVars)
err = json.Unmarshal([]byte(jsonVars), &gotVars)
assertNilError(t, err)

assertEqual(t, gotVars.LocationLine1, "514 Franklin Ave")
assertEqual(t, gotVars.LocationCityStateZip, "New Orleans, LA 70117")
assertEqual(t, gotVars.LocationMapURL, "https://www.google.com/maps/place/514+Franklin+Ave%2CNew+Orleans%2C+LA+70117")

w.Write([]byte("{}"))
_, err = w.Write([]byte("{}"))
assertNilError(t, err)

}))

mgSvc := NewMailgunService(
Expand Down
7 changes: 6 additions & 1 deletion notify/info_session.go
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,12 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
ctx := context.WithValue(r.Context(), RECIPIENT_TZ, tz)
var reqBody Request
reqBody.fromJSON(r.Body)
err = reqBody.fromJSON(r.Body)
if err != nil {
fmt.Printf("fromJSON: %v, bodyL%+v\n", err, reqBody)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}

// Remind attendees for some period in the future.
// (1 hour, 2 days, etc)
Expand Down
15 changes: 10 additions & 5 deletions notify/info_session_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,8 @@ func TestGetUpcomingSessions(t *testing.T) {
client: dbClient,
}

dropDatabase(context.Background(), mSrv)
err := dropDatabase(context.Background(), mSrv)
require.NoError(t, err)

// Insert 10 sessions over the next 10 days.
for daysInFuture := 1; daysInFuture <= 10; daysInFuture++ {
Expand Down Expand Up @@ -81,10 +82,12 @@ func TestGetUpcomingSessions(t *testing.T) {
client: dbClient,
}

dropDatabase(context.Background(), mSrv)
err := dropDatabase(context.Background(), mSrv)
require.NoError(t, err)

infoSessID := insertFutureSession(t, mSrv, time.Hour*24)
insertRandSignups(t, mSrv, infoSessID, 10)
err = insertRandSignups(t, mSrv, infoSessID, 10)
require.NoError(t, err)

daysOut := time.Hour * 24 * 10
got, err := mSrv.GetUpcomingSessions(context.Background(), daysOut)
Expand All @@ -103,10 +106,12 @@ func TestServer(t *testing.T) {
t.Run("Sends SMS messages to attendees of any upcoming sessions", func(t *testing.T) {
var body bytes.Buffer
e := json.NewEncoder(&body)
e.Encode(Request{
err := e.Encode(Request{
JobName: "info-session-reminder",
JobArgs: JobArgs{Period: "1 hour"},
})
require.NoError(t, err)

req := mustMakeReq(t, &body)
resp := httptest.NewRecorder()

Expand All @@ -127,7 +132,7 @@ func TestServer(t *testing.T) {
ZoomJoinURL: MustFakeZoomURL(t),
}

_, err := mongoService.client.Database(mongoService.dbName).Collection("signups").InsertOne(context.Background(), fakeSignup)
_, err = mongoService.client.Database(mongoService.dbName).Collection("signups").InsertOne(context.Background(), fakeSignup)
require.NoError(t, err)

mockTwilio := MockSMSService{}
Expand Down
3 changes: 2 additions & 1 deletion shorty_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ func TestShortenURL(t *testing.T) {

resp := ShortLink{ShortURL: wantURL, Code: shortCode, OriginalUrl: reqBody.OriginalUrl}
e := json.NewEncoder(w)
e.Encode(resp)
err = e.Encode(resp)
assertNilError(t, err)
}))

shorty := NewURLShortener(ShortenerOpts{mockSrv.URL, apiKey})
Expand Down
96 changes: 50 additions & 46 deletions signup_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,9 @@ func TestWelcomeData(t *testing.T) {
})
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
suSvc.attachZoomMeetingID(&test.signup)
err := suSvc.attachZoomMeetingID(&test.signup)
assertNilError(t, err)

test.signup.SetZoomJoinURL("https://us06web.zoom.us/w/fakemeetingid?tk=faketoken")
got, err := test.signup.welcomeData()
if err != nil {
Expand Down Expand Up @@ -612,50 +614,52 @@ func TestShortMessagingURL(t *testing.T) {
}

func TestCreateMessageURL(t *testing.T) {
mardiGras, err := time.Parse("Jan 02, 2006", "Feb 21, 2023") // Mardi Gras
require.NoError(t, err)

osLoc := Location{
Name: "Operation Spark",
Line1: "514 Franklin Av",
CityStateZip: "New Orleans, LA 70117",
MapURL: "https://testmapurl.google.com",
}
t.Run("creates a message URL with base64 encoded details", func(t *testing.T) {
mardiGras, err := time.Parse("Jan 02, 2006", "Feb 21, 2023") // Mardi Gras
require.NoError(t, err)

osLoc := Location{
Name: "Operation Spark",
Line1: "514 Franklin Av",
CityStateZip: "New Orleans, LA 70117",
MapURL: "https://testmapurl.google.com",
}

m := osMessenger{}
person := gofakeit.Person()
p := notify.Participant{
NameFirst: person.FirstName,
NameLast: person.LastName,
FullName: person.FirstName + " " + person.LastName,
Cell: person.Contact.Phone,
Email: person.Contact.Email,
ZoomJoinURL: notify.MustFakeZoomURL(t),
SessionDate: mardiGras,
SessionLocationType: "HYBRID",
SessionLocation: notify.Location(osLoc),
}
msgURL, err := m.CreateMessageURL(p)
require.NoError(t, err)
// Make sure location data is encoded in the URL
u, err := url.Parse(msgURL)
require.NoError(t, err)

// Decode the base64 encoded data from the generated URL
encoded := strings.TrimPrefix(u.Path, "/m/")
d := base64.NewDecoder(base64.StdEncoding, strings.NewReader(encoded))
decodedJson := make([]byte, 420)
n, err := d.Read(decodedJson)
require.Greater(t, n, 0)
require.NoError(t, err)

// Unmarshal the decoded JSON into a messaging request params struct
var params messagingReqParams
jd := json.NewDecoder(bytes.NewReader(decodedJson))
err = jd.Decode(&params)
require.NoError(t, err)

m := osMessenger{}
person := gofakeit.Person()
p := notify.Participant{
NameFirst: person.FirstName,
NameLast: person.LastName,
FullName: person.FirstName + " " + person.LastName,
Cell: person.Contact.Phone,
Email: person.Contact.Email,
ZoomJoinURL: notify.MustFakeZoomURL(t),
SessionDate: mardiGras,
SessionLocationType: "HYBRID",
SessionLocation: notify.Location(osLoc),
}
msgURL, err := m.CreateMessageURL(p)
require.NoError(t, err)
// Make sure location data is encoded in the URL
u, err := url.Parse(msgURL)
require.NoError(t, err)

// Decode the base64 encoded data from the generated URL
encoded := strings.TrimPrefix(u.Path, "/m/")
d := base64.NewDecoder(base64.StdEncoding, strings.NewReader(encoded))
decodedJson := make([]byte, 420)
n, err := d.Read(decodedJson)
require.Greater(t, n, 0)
require.NoError(t, err)

// Unmarshal the decoded JSON into a messaging request params struct
var params messagingReqParams
jd := json.NewDecoder(bytes.NewReader(decodedJson))
err = jd.Decode(&params)
require.NoError(t, err)

// Verify the location data matches the input from the Participant
require.Equal(t, "HYBRID", params.LocationType)
require.Equal(t, osLoc, params.Location)
// Verify the location data matches the input from the Participant
require.Equal(t, "HYBRID", params.LocationType)
require.Equal(t, osLoc, params.Location)
})
}
4 changes: 2 additions & 2 deletions slack_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ func TestSendWebhook(t *testing.T) {
slackAPI := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var payload body
d := json.NewDecoder(r.Body)
d.Decode(&payload)

err := d.Decode(&payload)
assertNilError(t, err)
assertEqual(t, payload["text"], msg.Text)
}))

Expand Down
3 changes: 2 additions & 1 deletion twilio_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@ func TestSendSMSInConversation(t *testing.T) {
conversationSid := os.Getenv("TWILIO_CONVERSATIONS_SID")

mockApi := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.ParseMultipartForm(128)
err := r.ParseMultipartForm(128)
assertNilError(t, err)

assertEqual(t, r.Form.Get("ShortenUrls"), "true")

Expand Down
10 changes: 8 additions & 2 deletions zoom.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,10 @@ func (z *zoomService) registerUser(ctx context.Context, su *Signup) error {

var respBody meeting.RegistrationResponse
d := json.NewDecoder(resp.Body)
d.Decode(&respBody)
err = d.Decode(&respBody)
if err != nil {
return fmt.Errorf("decode: %w", err)
}
su.SetZoomJoinURL(respBody.JoinURL)
return nil
}
Expand Down Expand Up @@ -165,7 +168,10 @@ func (z *zoomService) authenticate(ctx context.Context) error {

var body tokenResponse
d := json.NewDecoder(resp.Body)
d.Decode(&body)
err = d.Decode(&body)
if err != nil {
return fmt.Errorf("decode: %w", err)
}

z.accessToken = body.AccessToken
z.tokenExpiresAt = time.Now().Add(time.Second * time.Duration(body.ExpiresIn))
Expand Down
Loading

0 comments on commit f081812

Please sign in to comment.