Build a testable Go Web Application

Source: Internet
Author: User
Tags sourcegraph

Build a testable Go Web Application

Almost every programmer agrees that testing is important, but testing in a variety of ways can help write testers. They may run slowly and may use repeated code. Too many tests at a time may make it difficult to locate the root cause of the test failure.

In this article, we will discuss how to design the Sourcegraph unit test to make it simple to write, easy to maintain, fast to run, and accessible to others. We hope that some of the models mentioned here will help others who write Go web apps. We also welcome suggestions on our testing methods. Before starting the test, let's take a look at our framework overview.

Framework

Like other web apps, our website has three layers:

  • Web Front-end is used to serve HTML;

  • Http api is used to return JSON;

  • Data storage, run SQL queries on the database, and return the Go struct or slice.

When a user requests a Sourcegraph page, the front-end receives an HTTP page request and initiates a series of HTTP requests to the API server. Then, the API server starts querying the data storage. The data storage returns the data to the API server and then encodes it into JSON format and returns it to the web Front-End Server, the front-end uses the Go html/template package to display and format the data into HTML.

The frame chart is as follows: For more details, see recap of our Google I/O talk about building a large-scale code search engine in Go .)

 

Test v0

When we first started building Sourcegraph, we wrote the test in the easiest way to run. Each test enters the database and initiates an http get request to the test API endpoint. The test parses the HTTP returned content and compares it with the expected data. A typical v0 test is as follows:

 
 
  1. func TestListRepositories(t *testing.T) {  
  2.   tests := []struct { url string; insert []interface{}; want []*Repo }{  
  3.     {"/repos", []*Repo{{Name: "foo"}}, []*Repo{{Name: "foo"}}},  
  4.     {"/repos?lang=Go", []*Repo{{Lang: "Python"}}, nil},  
  5.     {"/repos?lang=Go", []*Repo{{Lang: "Go"}}, []*Repo{{Lang: "Go"}}},  
  6.   }  
  7.   db.Connect()  
  8.   s := http.NewServeMux()  
  9.   s.Handle("/", router)  
  10.   for _, test := range tests {  
  11.     func() {  
  12.       req, _ := http.NewRequest("GET", test.url, nil)  
  13.       tx, _ := db.DB.DbMap.Begin()  
  14.       defer tx.Rollback()  
  15.       tx.Insert(test.data...)  
  16.       rw := httptest.NewRecorder()  
  17.       rw.Body = new(bytes.Buffer)  
  18.       s.ServeHTTP(rw, req)  
  19.       var got []*Repo  
  20.       json.NewDecoder(rw.Body).Decode(&got)  
  21.       if !reflect.DeepEqual(got, want) {  
  22.         t.Errorf("%s: got %v, want %v", test.url, got, test.want)  
  23.       }  
  24.     }()  
  25.   }  

It was easy to write and test at the beginning, but it became painful as the app evolved. Over time, we added new features. More features lead to more tests, longer running time, and longer our dev cycle. More features also need to be changed and new URLs need to be added. Currently there are about 75 URLs), most of which are quite complicated. Each layer of Sourcegraph also becomes more complicated, so we want to test it independently of other layers.

We encountered some problems during the test:

1. Testing is slow because they want to interact with the actual database-insert test cases, initiate queries, and roll back each test transaction. Each test runs for about 100 milliseconds. As we add more tests.

2. Testing is difficult to refactor. The test uses a string to write the HTTP path and query parameters, which means that if we want to change a URL path or query the parameter set, we have to manually update the URL in the test. This pain will increase as the complexity and number of URL routes increase.

3. There are a large number of scattered and fragile sample codes. Install each test to ensure that the database runs normally and has the correct data. This code is used repeatedly in multiple cases, but the difference is sufficient to introduce bugs in the installation code. We found that we spent a lot of time debugging our tests instead of the actual app code.

4. It is difficult to diagnose a test failure. As the app becomes more complex, it is difficult to diagnose the root cause of test failure because each test accesses three application layers. Our tests are more like integration tests than unit tests.

Finally, we need to develop a public release API client. We want to make the API easy to be imitated so that our API users can also write test code.

Advanced testing objectives:

As our app evolves, we are aware of the need for tests that meet these high requirements:

  • Clear objectives:We need to test each layer of the app separately.

  • Comprehensive: All three layers of our app will be tested.

  • Fast: The test must run very quickly, meaning no database interaction is performed.

  • DRY: Although each layer of our apps is different, they share many common data structures. This is required for testing to eliminate duplicate sample code.

  • Easy to imitate: External API users should also be able to use our internal test mode. Projects built on the basis of our API should be able to easily write good tests. After all, our web Front-end is not unique-it is just another API user.

How do we recreate the test

Well-written, maintainable testing and well-maintained application code are inseparable. Refactoring the application code allows us to greatly improve our test code, which is the step for us to improve the test.

1. Build a Go http api Client

The first step in simplifying testing is to use Go to write a high-quality client for our APIs. Previously, our website was an AngularJS app, but because we mainly serve static content, we decided to move the front-end HTML generation to the server. After that, our new front-end can use the Go API client to communicate with the API server. Our client go-sourcegraph is open-source, and the go-github library has a huge impact on it. The client code, especially the endpoint code used to obtain the repository data) is as follows:

 
 
  1. func NewClient() *Client {  
  2.   c := &Client{BaseURL:DefaultBaseURL}  
  3.   c.Repositories = &repoService{c}  
  4.   return c  
  5. }  
  6.    
  7. type repoService struct{ c *Client }  
  8.    
  9. func (c *repoService) Get(name string) (*Repo, error) {  
  10.     resp, err := http.Get(fmt.Sprintf("%s/api/repos/%s", c.BaseURL, name))  
  11.     if err != nil {  
  12.         return nil, err  
  13.     }  
  14.     defer resp.Body.Close()  
  15.     var repo Repo  
  16.     return &repo, json.NewDecoder(resp.Body).Decode(&repo)  

In the past, our v0 API test killed a large number of URL paths and constructed HTTP requests in ad-hoc mode. Now they can use this API client to build and initiate requests.

2. Unified http api client and data warehouse Interfaces

Next, we will unify HTTP APIs and data warehouse interfaces. Previously, our API http. Handlers directly initiated SQL queries. Now our API http. Handlers only needs to parse http. Request and then call our data warehouse. The data warehouse and the http api client implement the same interface.

Using the above http api client (* repoService). Get method, we now have (* repoStore). Get:

 
 
  1. func NewDatastore(dbh modl.SqlExecutor) *Datastore {  
  2.   s := &Datastore{dbh: dbh}  
  3.   s.Repositories = &repoStore{s}  
  4.   return s  
  5. }  
  6.    
  7. type repoStore struct{ *Datastore }  
  8.    
  9. func (s *repoStore) Get(name string) (*Repo, error) {  
  10.     var repo *Repo  
  11.     return repo, s.db.Select(&repo, "SELECT * FROM repo WHERE name=$1", name)  

These interfaces are used to describe the behavior of our web app in one place, making it easier to understand and reason. In addition, we can reuse the same data type and parameter structure in the API client and data warehouse.

3. Centralized URL path Definition

Previously, we had to redefine the URL path at multiple layers of the application. In the API client, our code is as follows:

 
 
  1. resp, err := http.Get(fmt.Sprintf("%s/api/repos/%s", c.BaseURL, name)) 

This method can easily cause errors, because we have more than 75 path definitions, and many of them are complicated. The centralized URL path definition means that the path is reconstructed in a new package independently from the API server. The path package defines the path.

 
 
  1. const RepoGetRoute = "repo" 
  2.    
  3. func NewAPIRouter() *mux.Router {  
  4.     m := mux.NewRouter()  
  5.     // define the routes  
  6.     m.Path("/api/repos/{Name:.*}").Name(RepoGetRoute)  
  7.     return m  
  8. }  
  9.    
  10. while the http.Handlers were actually mounted in the API server package:  
  11.    
  12. func init() {  
  13.     m := NewAPIRouter()  
  14.     // mount handlers  
  15.     m.Get(RepoGetRoute).HandlerFunc(handleRepoGet)  
  16.     http.Handle("/api/", m)  

Http. Handlers is actually mounted in the API server package:

 
 
  1. func init() {  
  2.     m := NewAPIRouter()  
  3.     // mount handlers  
  4.     m.Get(RepoGetRoute).HandlerFunc(handleRepoGet)  
  5.     http.Handle("/api/", m)  

Now we can use the path package in the API client to generate URLs, instead of writing them to death. (* RepoService). Get method is as follows:

 
 
  1. var apiRouter = NewAPIRouter()  
  2.    
  3. func (s *repoService) Get(name string) (*Repo, error) {  
  4.     url, _ := apiRouter.Get(RepoGetRoute).URL("name", name)  
  5.     resp, err := http.Get(s.baseURL + url.String())  
  6.     if err != nil {  
  7.         return nil, err  
  8.     }  
  9.     defer resp.Body.Close()  
  10.    
  11.     var repo []Repo  
  12.     return repo, json.NewDecoder(resp.Body).Decode(&repo)  

4. Create a copy of an ununified Interface

In our v0 test, we also tested path, HTTP processing, SQL generation, and DB query. Failure is difficult to diagnose, and testing is also slow.

Now, we have independent tests on each layer and have imitated the functions of the adjacent layer. Because each layer of the application implements the same interface, we can use the same imitation interface in all the three layers.

The Imitation implementation is a simple simulated function structure, which can be specified in each test:

 
 
  1. type MockRepoService struct {  
  2.     Get_ func(name string) (*Repo, error)  
  3. }  
  4.    
  5. var _ RepoInterface = MockRepoService{}  
  6.    
  7. func (s MockRepoService) Get(name string) (*Repo, error) {  
  8.     if s.Get_ == nil {  
  9.         return nil, nil  
  10.     }  
  11.     return s.Get_(name)  
  12. }  
  13.    
  14. func NewMockClient() *Client { return &Client{&MockRepoService{}} } 

The following describes the application in the test. We mimic the RepoService of the data warehouse and use the http api client to test the API http. Handler. (This Code uses all of the above methods .)

 
 
  1. func TestRepoGet(t *testing.T) {  
  2.    setup()  
  3.    defer teardown()  
  4.    
  5.    var fetchedRepo bool  
  6.    mockDatastore.Repo.(*MockRepoService).Get_ = func(name string) (*Repo, error) {  
  7.        if name != "foo" {  
  8.            t.Errorf("want Get %q, got %q", "foo", repo.URI)  
  9.        }  
  10.        fetchedRepo = true 
  11.        return &Repo{name}, nil  
  12.    }  
  13.    
  14.    repo, err := mockAPIClient.Repositories.Get("foo")  
  15.    if err != nil { t.Fatal(err) }  
  16.    
  17.    if !fetchedRepo { t.Errorf("!fetchedRepo") }  

Review of advanced testing objectives

With the above model, we achieved the test goal. Our code is:

  • Clear objectives: One test layer.

  • Comprehensive: All three application layers are tested.

  • Fast: The test runs fast.

  • DRY: We have combined three common interfaces at the application layer and reused them in application code and testing.

  • Easy to imitate: One copy can be used in all three application layers. You can also use external APIs to test libraries built based on Sourcegraph.

The story about how to rebuild and improve the Sourcegraph test is complete. These models and examples run well in our environment. We hope these models and examples can also help others in the Go community, obviously, they are not correct in every scenario. We are sure there is room for improvement. We are constantly trying to improve our ways of doing things, so we are happy to hear your suggestions and feedback-let's talk about your experience in writing tests with Go!

From: http://www.oschina.net/translate/building-a-testable-webapp

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.