mercredi 5 février 2020

Testing that the API request is working golang

I am trying to add tests to my golang project. My program is saving JSON data into csv file. What I do is displaying my data on the screen (see the comment // STDOUT) and use a pipe that automatically creates the format file I want: go run main.go > file.csv, for example here I save the data into a csv file named file.csv

To be more clear, here is my code:

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
    "strconv"
    "strings"
)

type People struct {
    Name string
    Craft string
}

type General struct {
    People []People
    Number int
    Message string
}

func main() {
    // Reading data from JSON File  
    response, err := http.Get("http://api.open-notify.org/astros.json")
    if err != nil {
        fmt.Printf("The Http request failed with error %s\n", err)
    }

    data,_ := ioutil.ReadAll(response.Body)
    //fmt.Println(string(data))
    // Unmarshal JSON data
    var general General
    json.Unmarshal([]byte(data), &general)
    var header []string
    header = append(header, "Number")
    header = append(header, "Message")
    header = append(header, "Name")
    header = append(header, "Craft")
    fmt.Println(strings.Join(header, ","))
    for _, obj := range general.People {    
        var record []string
        record = append(record, strconv.Itoa(general.Number), general.Message)
        record = append(record, obj.Name, obj.Craft)
        fmt.Println(strings.Join(record, ",")) // STDOUT 
        record = nil
    }
}

So on my screen I obtain this output as expected:

Number,Message,Name,Craft
6,success,Christina Koch,ISS
6,success,Alexander Skvortsov,ISS
6,success,Luca Parmitano,ISS
6,success,Andrew Morgan,ISS
6,success,Oleg Skripochka,ISS
6,success,Jessica Meir,ISS

So I am wondering how I can test if this output is correctly displaying the datas I expect.

I tried to write a main_test.go file but I can't find out how to code it correctly.

package main

import (
    "testing"
    "net/http"
    "net/http/httptest"
)

func TestGetEntries(t *testing.T) {
    response, err := http.Get("http://api.open-notify.org/astros.json")
    if err != nil {
        t.Fatal(err)
    }
    // I don't know how to deal with this part:
    rr := httptest.NewRecorder()
    handler := http.HandlerFunc(main)
    handler.ServeHTTP(rr, req)
    if status := rr.Code; status != http.StatusOK {
        t.Errorf("handler returned wrong status code: got %v want %v",
            status, http.StatusOK)
    }

    // Check the response body is what we expect.
    // For example I want to test the first line:
    expected := `6,success,Christina Koch,ISS`
    if rr.Body.String() != expected {
        t.Errorf("handler returned unexpected body: got %v want %v",
            rr.Body.String(), expected)
    }
}

Aucun commentaire:

Enregistrer un commentaire