jeudi 27 août 2020

test ask how to solve this problem oh my god

테스트 글인데 어떄요 아래는 jaeger 용 go 테스트 코드

What are unit tests, integration tests, smoke tests, and regression tests? What are the differences between them and which tools can I use for each of them?

For example, I use JUnit and NUnit for unit testing and integration testing. Are there any tools for the last two, smoke testing or regression testing?

what's the matter~! what's the matter~!

what's the matter~!what's the matter~!what's the matter~! what's the matter~!what's the matter~! ???


    package main
    
    import (
        "database/sql"
        "errors"
        "fmt"
        "io/ioutil"
        "math/rand"
        "net/http"
        "time"
    
        "github.com/globalsign/mgo"
        "github.com/globalsign/mgo/bson"
    
        // "gopkg.in/mgo.v2"
        // "gopkg.in/mgo.v2/bson"
    
        "github.com/gorilla/mux"
        "github.com/opentracing/opentracing-go"
        "github.com/opentracing/opentracing-go/ext"
        "github.com/opentracing/opentracing-go/log"
    )
    
    func checkError(err error) {
        if err != nil {
            panic(err)
        }
    }
    
    //#################################################
    //router
    //#################################################
    type Mux struct {
        Router *mux.Router
    }
    
    func getRouter() *Mux {
        router := new(Mux)
        router.Router = mux.NewRouter()
    
        router.Router.HandleFunc("/bookstore", getBookStore).Methods("GET")
        router.Router.HandleFunc("/book", getBook).Methods("GET")
        router.Router.HandleFunc("/api/book", getApiBook).Methods("GET")
        router.Router.HandleFunc("/store", getStore).Methods("GET")
        router.Router.HandleFunc("/api/store", getApiStore).Methods("GET")
        router.Router.HandleFunc("/test/{id}", getTest).Methods("GET")
    
        return router
    }
    
    type key interface {
    }
    
    func getTest(w http.ResponseWriter, r *http.Request) {
    
        id := mux.Vars(r)["id"]
        res := "id2 : " + id
        fmt.Println(res)
    
        w.Write([]byte(res))
    }
    
    //#################################################
    //http get
    //#################################################
    func httpGet(url string, w http.ResponseWriter, r *http.Request) (string, error) {
        // fmt.Println("r.Host")
        // fmt.Println(r.Host)
    
        method := "GET"
    
        httpClient := &http.Client{}
        httpReq, err := http.NewRequest("GET", url, nil)
    
        //jaeger
        span, _ := opentracing.StartSpanFromContext(
            r.Context(),
            method+"_"+url,
            ext.SpanKindRPCClient)
    
        span.SetTag(string(ext.Component), "http")
        span.SetTag(string(ext.HTTPUrl), url)
        span.SetTag(string(ext.HTTPMethod), method)
        span.SetTag(string(ext.PeerService), TARGET)
    
        if r != nil {
            span.SetTag(HTTP_REQ_HEADER, GetSpanTagReqHeader(r))
            span.SetTag(HTTP_REQ_BODY, GetSpanTagReqBody(r))
        }
    
        span.LogFields(
            log.String("event", "INFO"),
            log.String("message", "Go test log message"),
        )
    
        defer span.Finish()
    
        opentracing.GlobalTracer().Inject(
            span.Context(),
            opentracing.HTTPHeaders,
            opentracing.HTTPHeadersCarrier(httpReq.Header))
    
        fmt.Println("httpReq.Header : ")
        fmt.Println(httpReq.Header)
        //jaeger
    
        res, err := httpClient.Do(httpReq)
    
        // res, err := http.Get(url)
        if err != nil {
            fmt.Println("Error :", err.Error())
            span.SetTag(string(ext.Error), true)
            span.SetTag(string(ext.HTTPStatusCode), 500)
            span.LogFields(
                log.String("event", "error"),
                log.Object("error.object", err),
                log.String("message", err.Error()))
    
            return "Error: " + err.Error(), err
        }
        defer res.Body.Close()
    
        //jaeger
        span.SetTag(string(ext.HTTPStatusCode), res.StatusCode)
        span.SetTag(HTTP_RES_HEADER, GetSpanTagResHeader(res))
        span.SetTag(HTTP_RES_BODY, GetSpanTagResBody(res))
        if res.StatusCode >= 400 {
            span.SetTag(string(ext.Error), true)
            // w.WriteHeader(res.StatusCode)
        }
        //jaeger
    
        body, _ := ioutil.ReadAll(res.Body)
    
        result := string(body)
        fmt.Println("res from api book : " + result)
    
        return result, nil
    }
    
    //#################################################
    //bookstore
    //#################################################
    func getBookStore(w http.ResponseWriter, r *http.Request) {
        fmt.Println("----------------------------------------------")
        fmt.Println("getBookStore called")
        var result string
    
        //########################
        //##### random error #####
        //########################
        rand.Seed(time.Now().UnixNano())
        i := rand.Intn(100)
        md := i % 10
        fmt.Println("random number:", i, "/ mod:", md)
        if md == 1 {
            fmt.Println("status code:", 400)
            fmt.Println("error msg:", "Random Invalid Param")
            w.WriteHeader(400)
            w.Write([]byte("Random Invalid Param"))
            return
        } else if md == 2 {
            fmt.Println("status code:", 500)
            fmt.Println("error msg:", "Random Server Error")
            w.WriteHeader(500)
            w.Write([]byte("Random Server Error"))
            return
        }
        //##### random error #####
    
        //book
        url := remote + "/book"
        fmt.Println("call remote : " + url)
    
        result, err := httpGet(url, w, r)
        if err != nil {
            w.WriteHeader(500)
            w.Write([]byte(err.Error()))
            return
        }
    
        //self
        result2, err := getBookData()
        if err != nil {
            w.WriteHeader(500)
            w.Write([]byte(err.Error()))
            return
        }
    
        result += "\n" + result2
    
        //store
        url = remote + "/store"
        fmt.Println("call remote : " + url)
    
        result3, err := httpGet(url, w, r)
        if err != nil {
            w.WriteHeader(500)
            w.Write([]byte(err.Error()))
            return
        }
    
        result += "\n" + result3
    
        //self
        result4, err := getStoreData()
        if err != nil {
            w.WriteHeader(500)
            w.Write([]byte(err.Error()))
            return
        }
        result += "\n" + result4
    
        w.Write([]byte(result))
    }
    
    //#################################################
    // book
    //#################################################
    func getBook(w http.ResponseWriter, r *http.Request) {
        fmt.Println("----------------------------------------------")
        fmt.Println("/book called")
        url := remote + "/api/book"
        fmt.Println("call remote : " + url)
    
        //########################
        //##### random error #####
        //########################
        rand.Seed(time.Now().UnixNano())
        i := rand.Intn(100)
        md := i % 10
        fmt.Println("random number:", i, "/ mod:", md)
        if md == 1 {
            fmt.Println("status code:", 400)
            fmt.Println("error msg:", "Random Invalid Param")
            w.WriteHeader(400)
            w.Write([]byte("Random Invalid Param"))
            return
        } else if md == 2 {
            fmt.Println("status code:", 500)
            fmt.Println("error msg:", "Random Server Error")
            w.WriteHeader(500)
            w.Write([]byte("Random Server Error"))
            return
        }
        //##### random error #####
    
        result, err := httpGet(url, w, r)
        if err != nil {
            w.WriteHeader(500)
            w.Write([]byte(err.Error()))
            return
        }
    
        body2, err := getBookData()
        if err != nil {
            w.WriteHeader(500)
            w.Write([]byte(err.Error()))
            return
        }
    
        val := result + "\n" + body2
    
        fmt.Println(string(val))
    
        w.Write([]byte(val))
    }
    
    //#################################################
    // book api
    //#################################################
    func getApiBook(w http.ResponseWriter, r *http.Request) {
        fmt.Println("----------------------------------------------")
        fmt.Println("/api/book called")
    
        res, err := getBookData()
        if err != nil {
            w.WriteHeader(500)
            w.Write([]byte(err.Error()))
            return
        }
    
        fmt.Println(res)
    
        w.Write([]byte(res))
    }
    
    //#################################################
    // book data
    //#################################################
    func getBookData() (string, error) {
        // var connectionString string = fmt.Sprintf("host=%s user=%s password=%s dbname=%s sslmode=disable", HOST, USER, PASSWORD, DATABASE)
        // // Initialize connection object.
        // db, err := sql.Open("postgres", connectionString)
        // checkError(err)
    
        //########################
        //##### random error #####
        //########################
        rand.Seed(time.Now().UnixNano())
        i := rand.Intn(100)
        md := i % 10
        fmt.Println("random number:", i, "/ mod:", md)
        if md == 1 {
            fmt.Println("status code:", 500)
            fmt.Println("error msg:", "Get Book Data Error")
            return "", errors.New("Random Book Data Error")
        }
        //##### random error #####
    
        err := DB.Ping()
        if err != nil {
            return "", errors.New("DB Ping Error")
        }
        // checkError(err)
        // fmt.Println("Successfully created connection to database")
    
        q := "SELECT book_title FROM books;"
        rows, err := DB.Query(q)
        if err != nil {
            return "", errors.New("DB Query Error")
        }
        // checkError(err)
        defer rows.Close()
    
        var res string
        var title string
        for rows.Next() {
            switch err := rows.Scan(&title); err {
            case sql.ErrNoRows:
                fmt.Println("No rows were returned")
            case nil:
                res += title + ", "
            default:
                return "", errors.New("Row Scan Error")
                // checkError(err)
            }
        }
        res = "[from Go]      book : " + res
        return res, nil
    }
    
    //#################################################
    // store
    //#################################################
    func getStore(w http.ResponseWriter, r *http.Request) {
        fmt.Println("----------------------------------------------")
        fmt.Println("/store called")
    
        url := remote + "/api/store"
        fmt.Println("call remote : " + url)
    
        result, err := httpGet(url, w, r)
        if err != nil {
            w.WriteHeader(500)
            w.Write([]byte(result))
            return
        }
    
        body2, err := getStoreData()
        if err != nil {
            w.WriteHeader(500)
            w.Write([]byte(err.Error()))
            return
        }
        val := result + "\n" + body2
    
        fmt.Println(string(val))
    
        w.Write([]byte(val))
    }
    
    //#################################################
    // store api
    //#################################################
    func getApiStore(w http.ResponseWriter, r *http.Request) {
        fmt.Println("----------------------------------------------")
        fmt.Println("/api/store called")
    
        res, err := getStoreData()
        if err != nil {
            w.WriteHeader(500)
            w.Write([]byte(err.Error()))
            return
        }
        fmt.Println(res)
    
        w.Write([]byte(res))
    }
    
    //#################################################
    // store data
    //#################################################
    func getStoreData() (string, error) {
        session, err := mgo.Dial("192.168.10.130")
        if err != nil {
            return "", errors.New("Mongo dial error.")
            // panic(err)
        }
    
        defer session.Close()
    
        session.SetSafe(&mgo.Safe{})
    
        // println("#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@  st1")
        // var st mgo.Stats
        // println("#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@  st2")
        // st = mgo.GetStats
        // println("########## :: Clusters", st.Clusters)
        // println("#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@  ed")
    
        c := session.DB("test").C("stores")
    
        type Store struct {
            NO   int    `bson:"store_no"`
            NAME string `bson:"store_name"`
        }
    
        result := Store{}
        // fmt.Println("Getting  data....")
        iter := c.Find(bson.M{}).Iter()
        var index = 1
    
        var res string
        for iter.Next(&result) {
            // fmt.Printf("current result is [%d] result =%+v\n", index, result)
            res += result.NAME + ", "
            index++
        }
        res = "[from Go]     store : " + res
    
        if err2 := iter.Close(); err2 != nil {
            fmt.Printf("No data\n")
            return "", errors.New("Mongo close error.")
        }
    
        return res, nil
    }

Aucun commentaire:

Enregistrer un commentaire