Skip to content

Add hw4_test_coverage solution #7

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
135 changes: 135 additions & 0 deletions hw4_test_coverage/client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
package main

import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/url"
"strconv"
"time"
)

const (
orderAsc = iota
orderDesc
)

var (
errTest = errors.New("testing")
client = &http.Client{Timeout: time.Second}
)

type User struct {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

exported type User should have comment or be unexported

Id int
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

struct field Id should be ID

Name string
Age int
About string
Gender string
}

type SearchResponse struct {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

exported type SearchResponse should have comment or be unexported

Users []User
NextPage bool
}

type SearchErrorResponse struct {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

exported type SearchErrorResponse should have comment or be unexported

Error string
}

const (
OrderByAsc = -1
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

exported const OrderByAsc should have comment (or a comment on this block) or be unexported

OrderByAsIs = 0
OrderByDesc = 1

ErrorBadOrderField = `OrderField invalid`
)

type SearchRequest struct {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

exported type SearchRequest should have comment or be unexported

Limit int
Offset int // Можно учесть после сортировки
Query string // подстрока в 1 из полей
OrderField string
// -1 по убыванию, 0 как встретилось, 1 по возрастанию
OrderBy int
}

type SearchClient struct {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

exported type SearchClient should have comment or be unexported

// токен, по которому происходит авторизация на внешней системе, уходит туда через хедер
AccessToken string
// урл внешней системы, куда идти
URL string
}

// FindUsers отправляет запрос во внешнюю систему, которая непосредственно ищет пользоваталей
func (srv *SearchClient) FindUsers(req SearchRequest) (*SearchResponse, error) {

searcherParams := url.Values{}

if req.Limit < 0 {
return nil, fmt.Errorf("limit must be > 0")
}
if req.Limit > 25 {
req.Limit = 25
}
if req.Offset < 0 {
return nil, fmt.Errorf("offset must be > 0")
}

//нужно для получения следующей записи, на основе которой мы скажем - можно показать переключатель следующей страницы или нет
req.Limit++

searcherParams.Add("limit", strconv.Itoa(req.Limit))
searcherParams.Add("offset", strconv.Itoa(req.Offset))
searcherParams.Add("query", req.Query)
searcherParams.Add("order_field", req.OrderField)
searcherParams.Add("order_by", strconv.Itoa(req.OrderBy))

searcherReq, err := http.NewRequest("GET", srv.URL+"?"+searcherParams.Encode(), nil)
searcherReq.Header.Add("AccessToken", srv.AccessToken)

resp, err := client.Do(searcherReq)
if err != nil {
if err, ok := err.(net.Error); ok && err.Timeout() {
return nil, fmt.Errorf("timeout for %s", searcherParams.Encode())
}
return nil, fmt.Errorf("unknown error %s", err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)

switch resp.StatusCode {
case http.StatusUnauthorized:
return nil, fmt.Errorf("Bad AccessToken")
case http.StatusInternalServerError:
return nil, fmt.Errorf("SearchServer fatal error")
case http.StatusBadRequest:
errResp := SearchErrorResponse{}
err = json.Unmarshal(body, &errResp)
if err != nil {
return nil, fmt.Errorf("cant unpack error json: %s", err)
}
if errResp.Error == "ErrorBadOrderField" {
return nil, fmt.Errorf("OrderFeld %s invalid", req.OrderField)
}
return nil, fmt.Errorf("unknown bad request error: %s", errResp.Error)
}

data := []User{}
err = json.Unmarshal(body, &data)
if err != nil {
return nil, fmt.Errorf("cant unpack result json: %s", err)
}

result := SearchResponse{}
if len(data) == req.Limit {
result.NextPage = true
result.Users = data[0 : len(data)-1]
} else {
result.Users = data[0:len(data)]
}

return &result, err
}
182 changes: 182 additions & 0 deletions hw4_test_coverage/client_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
package main

import (
"encoding/json"
"encoding/xml"
"fmt"
"io"
"net/http"
"net/http/httptest"
"os"
"reflect"
"sort"
"strconv"
"strings"
"testing"
)

type UserXML struct {
ID int `xml:"id"`
FirstName string `xml:"first_name"`
LastName string `xml:"last_name"`
Age int `xml:"age"`
About string `xml:"about"`
Gender string `xml:"gender"`
}

var usersXML []UserXML
var users []User
var filePath = "dataset.xml"

func SearchServer(w http.ResponseWriter, r *http.Request) {
file, _ := os.Open(filePath)

orderField := r.FormValue("order_field")
if orderField == "" {
orderField = "Name"
} else if orderField != "Id" && orderField != "Name" && orderField != "Age" {
w.WriteHeader(http.StatusInternalServerError)
}

query := r.FormValue("query")
offset, _ := strconv.Atoi(r.FormValue("offset"))
limit, _ := strconv.Atoi(r.FormValue("limit"))
orderBy, _ := strconv.Atoi(r.FormValue("order_by"))

decoder := xml.NewDecoder(file)

if len(usersXML) == 0 {
for {
var userXML UserXML
tok, tokenErr := decoder.Token()
if tokenErr != nil && tokenErr != io.EOF {
fmt.Println("error happend", tokenErr)
break
} else if tokenErr == io.EOF {
break
}
if tok == nil {
fmt.Println("t is nil break")
}
switch tok := tok.(type) {
case xml.StartElement:
if tok.Name.Local == "row" {
if err := decoder.DecodeElement(&userXML, &tok); err != nil {
fmt.Println("error happend", err)
}
usersXML = append(usersXML, userXML)
}
}
}
}

var shortUsersXML []UserXML

for _, userXML := range usersXML {
if len(query) > 0 {
if strings.Contains(userXML.FirstName, query) || strings.Contains(userXML.LastName, query) || strings.Contains(userXML.About, query) {
shortUsersXML = append(shortUsersXML, userXML)
}
} else {
shortUsersXML = append(shortUsersXML, userXML)
}
}

sort.Slice(shortUsersXML, func(i, j int) bool {
if orderField == "Name" {
if shortUsersXML[i].FirstName < shortUsersXML[j].FirstName {
return true
}
if shortUsersXML[i].FirstName > shortUsersXML[j].FirstName {
return false
}
return shortUsersXML[i].LastName < shortUsersXML[j].LastName
}
iValue := reflect.Indirect(reflect.ValueOf(&shortUsersXML[i])).FieldByName(orderField)
jValue := reflect.Indirect(reflect.ValueOf(&shortUsersXML[j])).FieldByName(orderField)
if orderBy == -1 {
return int(iValue.Int()) > int(jValue.Int())
} else if orderBy == 1 {
return int(iValue.Int()) < int(jValue.Int())
}
return true
})

for _, userXML := range shortUsersXML {
users = append(users, User{
Id: userXML.ID,
Name: userXML.FirstName + " " + userXML.LastName,
Age: userXML.Age,
About: userXML.About,
Gender: userXML.Gender,
})
}

limitedOffsettedUsers := users[offset : offset+limit]

w.WriteHeader(http.StatusOK)
json, _ := json.Marshal(limitedOffsettedUsers)
io.WriteString(w, string(json[:]))
}

type TestCase struct {
SearchRequest *SearchRequest
Result *SearchResponse
IsError bool
}

func TestSearchClientFindUsers(t *testing.T) {
cases := []TestCase{
TestCase{
SearchRequest: &SearchRequest{
Limit: 1,
Offset: 1, // Можно учесть после сортировки
Query: "tt", // подстрока в 1 из полей
OrderField: "Name",
OrderBy: 1, // -1 по убыванию, 0 как встретилось, 1 по возрастанию
},
Result: &SearchResponse{
Users: []User{
User{
Id: 3,
Name: "Everett Dillard",
Age: 27,
About: "Sint eu id sint irure officia amet cillum. Amet consectetur enim mollit culpa laborum ipsum adipisicing est laboris." +
" Adipisicing fugiat esse dolore aliquip quis laborum aliquip dolore. Pariatur do elit eu nostrud occaecat.\n",
Gender: "male",
},
},
NextPage: true,
},
IsError: false,
},
TestCase{
SearchRequest: &SearchRequest{
OrderField: "asd",
},
Result: nil,
IsError: true,
},
}

ts := httptest.NewServer(http.HandlerFunc(SearchServer))

for caseNum, caseItem := range cases {
client := &SearchClient{
URL: ts.URL,
AccessToken: "accessToken",
}
result, err := client.FindUsers(*caseItem.SearchRequest)

if err != nil && !caseItem.IsError {
t.Errorf("[%d] unexpected error: %#v", caseNum, err)
}
if err == nil && caseItem.IsError {
t.Errorf("[%d] expected error, got nil", caseNum)
}
if !reflect.DeepEqual(caseItem.Result, result) {
t.Errorf("[%d] wrong result, expected %#v, got %#v", caseNum, caseItem.Result, result)
}
}
ts.Close()
}
Loading