返回

go-如何使用gorm进行单元测试

发布时间:2022-04-13 13:51:00 325
# python

我是新来的Gounit test.在我的项目中,我使用Go具有gorm和连接mysql数据库

我的问题是如何对代码进行单元测试:

我的代码如下(main.go):

package main

import (
    "encoding/json"
    "fmt"
    "net/http"
    "strconv"
    "time"

    "github.com/gorilla/mux"
    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/mysql"
)

type Jobs struct {
    JobID                  uint   `json: "jobId" gorm:"primary_key;auto_increment"`
    SourcePath             string `json: "sourcePath"`
    Priority               int64  `json: "priority"`
    InternalPriority       string `json: "internalPriority"`
    ExecutionEnvironmentID string `json: "executionEnvironmentID"`
}

type ExecutionEnvironment struct {
    ID                     uint      `json: "id" gorm:"primary_key;auto_increment"`
    ExecutionEnvironmentId string    `json: "executionEnvironmentID"`
    CloudProviderType      string    `json: "cloudProviderType"`
    InfrastructureType     string    `json: "infrastructureType"`
    CloudRegion            string    `json: "cloudRegion"`
    CreatedAt              time.Time `json: "createdAt"`
}

var db *gorm.DB

func initDB() {
    var err error
    dataSourceName := "root:@tcp(localhost:3306)/?parseTime=True"
    db, err = gorm.Open("mysql", dataSourceName)

    if err != nil {
        fmt.Println(err)
        panic("failed to connect database")
    }
    //db.Exec("CREATE DATABASE test")
    db.LogMode(true)
    db.Exec("USE test")
    db.AutoMigrate(&Jobs{}, &ExecutionEnvironment{})
}

func GetAllJobs(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    fmt.Println("Executing Get All Jobs function")

    var jobs []Jobs
    if err := db.Select("jobs.*, execution_environments.*").Joins("JOIN execution_environments on execution_environments.execution_environment_id = jobs.execution_environment_id").Find(&jobs).Error; err != nil {
        fmt.Println(err)
    }
    fmt.Println()
    if len(jobs) == 0 {
        json.NewEncoder(w).Encode("No data found")
    } else {
        json.NewEncoder(w).Encode(jobs)
    }
}

// create job
func createJob(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    fmt.Println("Executing Create Jobs function")
    var jobs Jobs
    json.NewDecoder(r.Body).Decode(&jobs)
    db.Create(&jobs)
    json.NewEncoder(w).Encode(jobs)
}

// get job by id
func GetJobById(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    params := mux.Vars(r)
    jobId := params["jobId"]

    //var job []Jobs
    //db.Preload("Items").First(&job, jobId)
    var jobs []Jobs
    var executionEnvironments []ExecutionEnvironment
    if err := db.Table("jobs").Select("jobs.*, execution_environments.*").Joins("JOIN execution_environments on execution_environments.execution_environment_id = jobs.execution_environment_id").Where("job_id =?", jobId).Find(&jobs).Scan(&executionEnvironments).Error; err != nil {
        fmt.Println(err)
    }

    if len(jobs) == 0 {
        json.NewEncoder(w).Encode("No data found")
    } else {
        json.NewEncoder(w).Encode(jobs)
    }
}

// Delete Job By Id
func DeleteJobById(w http.ResponseWriter, r *http.Request) {
    params := mux.Vars(r)
    jobId := params["jobId"]

    // check data
    var job []Jobs
    db.Table("jobs").Select("jobs.*").Where("job_id=?", jobId).Find(&job)
    if len(job) == 0 {
        json.NewEncoder(w).Encode("Invalid JobId")
    } else {

        id64, _ := strconv.ParseUint(jobId, 10, 64)
        idToDelete := uint(id64)

        db.Where("job_id = ?", idToDelete).Delete(&Jobs{})
        //db.Where("jobId = ?", idToDelete).Delete(&ExecutionEnvironment{})

        json.NewEncoder(w).Encode("Job deleted successfully")
        w.WriteHeader(http.StatusNoContent)
    }

}

// create Execution Environments
func createEnvironments(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    fmt.Println("Executing Create Execution Environments function")
    var executionEnvironments ExecutionEnvironment
    json.NewDecoder(r.Body).Decode(&executionEnvironments)
    db.Create(&executionEnvironments)
    json.NewEncoder(w).Encode(executionEnvironments)
}

// Get Job Cloud Region
func GetJobCloudRegion(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    fmt.Println("Executing Get Job Cloud Region function")

    params := mux.Vars(r)
    jobId := params["jobId"]

    //var jobs []Jobs
    var executionEnvironment []ExecutionEnvironment

    db.Table("jobs").Select("execution_environments.*").Joins("JOIN execution_environments on execution_environments.execution_environment_id = jobs.execution_environment_id").Where("jobs.job_id =?", jobId).Find(&executionEnvironment)

    var pUuid []string
    for _, uuid := range executionEnvironment {
        pUuid = append(pUuid, uuid.CloudRegion)
    }
    json.NewEncoder(w).Encode(pUuid)

}

func main() {
    // router
    router := mux.NewRouter()
    // Access URL
    router.HandleFunc("/GetAllJobs", GetAllJobs).Methods("GET")
    router.HandleFunc("/createJob", createJob).Methods("POST")
    router.HandleFunc("/GetJobById/{jobId}", GetJobById).Methods("GET")
    router.HandleFunc("/DeleteJobById/{jobId}", DeleteJobById).Methods("DELETE")

    router.HandleFunc("/createEnvironments", createEnvironments).Methods("POST")
    router.HandleFunc("/GetJobCloudRegion/{jobId}", GetJobCloudRegion).Methods("GET")

    // Initialize db connection
    initDB()

    // config port
    fmt.Printf("Starting server at 8000 \n")
    http.ListenAndServe(":8000", router)
}

我试图在下面创建单元测试文件,但它并没有像这样运行enter image description here

主测试。开始:

package main

import (
    "log"
    "os"
    "testing"

    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/mysql"
)

func TestinitDB(m *testing.M) {
    dataSourceName := "root:@tcp(localhost:3306)/?parseTime=True"
    db, err := gorm.Open("mysql", dataSourceName)

    if err != nil {
        log.Fatal("failed to connect database")
    }
    //db.Exec("CREATE DATABASE test")
    db.LogMode(true)
    db.Exec("USE test111")
    os.Exit(m.Run())
}

请帮我写单元测试文件

特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(0)
按点赞数排序
用户头像