Best K6 code snippet using http.Error
rest_api_test.go
Source:rest_api_test.go
...27)28func performHTTPGet(t *testing.T, url string) []byte {29 response, err := http.Get(url)30 if err != nil {31 t.Fatalf("Error attempt to GET %s: %v", url, err)32 }33 body, err := ioutil.ReadAll(response.Body)34 response.Body.Close()35 if err != nil {36 t.Fatalf("Error reading HTTP resposne body: %v", err)37 }38 return body39}40func performHTTPPost(t *testing.T, url string, requestBody []byte) (*http.Response, []byte) {41 response, err := http.Post(url, "application/json", bytes.NewReader(requestBody))42 if err != nil {43 t.Fatalf("Error attempt to POST %s: %v", url, err)44 }45 body, err := ioutil.ReadAll(response.Body)46 response.Body.Close()47 if err != nil {48 t.Fatalf("Error reading HTTP resposne body: %v", err)49 }50 return response, body51}52func performHTTPDelete(t *testing.T, url string) []byte {53 req, err := http.NewRequest(http.MethodDelete, url, nil)54 if err != nil {55 t.Fatalf("Error building a DELETE request")56 }57 response, err := http.DefaultClient.Do(req)58 if err != nil {59 t.Fatalf("Error attempt to DELETE %s: %v", url, err)60 }61 body, err := ioutil.ReadAll(response.Body)62 response.Body.Close()63 if err != nil {64 t.Fatalf("Error reading HTTP resposne body: %v", err)65 }66 return body67}68func parseRESTResult(t *testing.T, body []byte) restResult {69 var res restResult70 err := json.Unmarshal(body, &res)71 if err != nil {72 t.Fatalf("Invalid JSON response: %v", err)73 }74 return res75}76func parseRPCResponse(t *testing.T, body []byte) rpcResponse {77 var res rpcResponse78 err := json.Unmarshal(body, &res)79 if err != nil {80 t.Fatalf("Invalid JSON RPC response: %v", err)81 }82 return res83}84type mockDevops struct {85}86func (d *mockDevops) Login(c context.Context, s *protos.Secret) (*protos.Response, error) {87 if s.EnrollSecret == "wrong_password" {88 return &protos.Response{Status: protos.Response_FAILURE, Msg: []byte("Wrong mock password")}, nil89 }90 return &protos.Response{Status: protos.Response_SUCCESS}, nil91}92func (d *mockDevops) Build(c context.Context, cs *protos.ChaincodeSpec) (*protos.ChaincodeDeploymentSpec, error) {93 return nil, nil94}95func (d *mockDevops) Deploy(c context.Context, spec *protos.ChaincodeSpec) (*protos.ChaincodeDeploymentSpec, error) {96 if spec.ChaincodeID.Path == "non-existing" {97 return nil, fmt.Errorf("Deploy failure on non-existing path")98 }99 spec.ChaincodeID.Name = "new_name_for_deployed_chaincode"100 return &protos.ChaincodeDeploymentSpec{ChaincodeSpec: spec, CodePackage: []byte{}}, nil101}102func (d *mockDevops) Invoke(c context.Context, cis *protos.ChaincodeInvocationSpec) (*protos.Response, error) {103 switch cis.ChaincodeSpec.CtorMsg.Function {104 case "fail":105 return nil, fmt.Errorf("Invoke failure")106 case "change_owner":107 return &protos.Response{Status: protos.Response_SUCCESS, Msg: []byte("change_owner_invoke_result")}, nil108 }109 return nil, fmt.Errorf("Unknown function invoked")110}111func (d *mockDevops) Query(c context.Context, cis *protos.ChaincodeInvocationSpec) (*protos.Response, error) {112 switch cis.ChaincodeSpec.CtorMsg.Function {113 case "fail":114 return nil, fmt.Errorf("Query failure with special-\" chars")115 case "get_owner":116 return &protos.Response{Status: protos.Response_SUCCESS, Msg: []byte("get_owner_query_result")}, nil117 }118 return nil, fmt.Errorf("Unknown query function")119}120func (d *mockDevops) EXP_GetApplicationTCert(ctx context.Context, secret *protos.Secret) (*protos.Response, error) {121 return nil, nil122}123func (d *mockDevops) EXP_PrepareForTx(ctx context.Context, secret *protos.Secret) (*protos.Response, error) {124 return nil, nil125}126func (d *mockDevops) EXP_ProduceSigma(ctx context.Context, sigmaInput *protos.SigmaInput) (*protos.Response, error) {127 return nil, nil128}129func (d *mockDevops) EXP_ExecuteWithBinding(ctx context.Context, executeWithBinding *protos.ExecuteWithBinding) (*protos.Response, error) {130 return nil, nil131}132func initGlobalServerOpenchain(t *testing.T) {133 var err error134 serverOpenchain, err = NewOpenchainServerWithPeerInfo(new(peerInfo))135 if err != nil {136 t.Fatalf("Error creating OpenchainServer: %s", err)137 }138 serverDevops = new(mockDevops)139}140func TestServerOpenchainREST_API_GetBlockchainInfo(t *testing.T) {141 // Construct a ledger with 0 blocks.142 ledger := ledger.InitTestLedger(t)143 initGlobalServerOpenchain(t)144 // Start the HTTP REST test server145 httpServer := httptest.NewServer(buildOpenchainRESTRouter())146 defer httpServer.Close()147 body := performHTTPGet(t, httpServer.URL+"/chain")148 res := parseRESTResult(t, body)149 if res.Error == "" {150 t.Errorf("Expected an error when retrieving empty blockchain, but got none")151 }152 // add 3 blocks to the ledger153 buildTestLedger1(ledger, t)154 body3 := performHTTPGet(t, httpServer.URL+"/chain")155 var blockchainInfo3 protos.BlockchainInfo156 err := json.Unmarshal(body3, &blockchainInfo3)157 if err != nil {158 t.Fatalf("Invalid JSON response: %v", err)159 }160 if blockchainInfo3.Height != 3 {161 t.Errorf("Expected blockchain height to be 3 but got %v", blockchainInfo3.Height)162 }163 // add 5 more blocks more to the ledger164 buildTestLedger2(ledger, t)165 body8 := performHTTPGet(t, httpServer.URL+"/chain")166 var blockchainInfo8 protos.BlockchainInfo167 err = json.Unmarshal(body8, &blockchainInfo8)168 if err != nil {169 t.Fatalf("Invalid JSON response: %v", err)170 }171 if blockchainInfo8.Height != 8 {172 t.Errorf("Expected blockchain height to be 8 but got %v", blockchainInfo8.Height)173 }174}175func TestServerOpenchainREST_API_GetBlockByNumber(t *testing.T) {176 // Construct a ledger with 0 blocks.177 ledger := ledger.InitTestLedger(t)178 initGlobalServerOpenchain(t)179 // Start the HTTP REST test server180 httpServer := httptest.NewServer(buildOpenchainRESTRouter())181 defer httpServer.Close()182 body := performHTTPGet(t, httpServer.URL+"/chain/blocks/0")183 res := parseRESTResult(t, body)184 if res.Error == "" {185 t.Errorf("Expected an error when retrieving block 0 of an empty blockchain, but got none")186 }187 // add 3 blocks to the ledger188 buildTestLedger1(ledger, t)189 // Retrieve the first block from the blockchain (block number = 0)190 body0 := performHTTPGet(t, httpServer.URL+"/chain/blocks/0")191 var block0 protos.Block192 err := json.Unmarshal(body0, &block0)193 if err != nil {194 t.Fatalf("Invalid JSON response: %v", err)195 }196 // Retrieve the 3rd block from the blockchain (block number = 2)197 body2 := performHTTPGet(t, httpServer.URL+"/chain/blocks/2")198 var block2 protos.Block199 err = json.Unmarshal(body2, &block2)200 if err != nil {201 t.Fatalf("Invalid JSON response: %v", err)202 }203 if len(block2.Transactions) != 2 {204 t.Errorf("Expected block to contain 2 transactions but got %v", len(block2.Transactions))205 }206 // Retrieve the 5th block from the blockchain (block number = 4), which207 // should fail because the ledger has only 3 blocks.208 body4 := performHTTPGet(t, httpServer.URL+"/chain/blocks/4")209 res4 := parseRESTResult(t, body4)210 if res4.Error == "" {211 t.Errorf("Expected an error when retrieving non-existing block, but got none")212 }213 // Illegal block number214 body = performHTTPGet(t, httpServer.URL+"/chain/blocks/NOT_A_NUMBER")215 res = parseRESTResult(t, body)216 if res.Error == "" {217 t.Errorf("Expected an error when URL doesn't have a number, but got none")218 }219 // Add a fake block number 9 and try to fetch non-existing block 6220 ledger.PutRawBlock(&block0, 9)221 body = performHTTPGet(t, httpServer.URL+"/chain/blocks/6")222 res = parseRESTResult(t, body)223 if res.Error == "" {224 t.Errorf("Expected an error when block doesn't exist, but got none")225 }226}227func TestServerOpenchainREST_API_GetTransactionByUUID(t *testing.T) {228 startTime := time.Now().Unix()229 // Construct a ledger with 3 blocks.230 ledger := ledger.InitTestLedger(t)231 buildTestLedger1(ledger, t)232 initGlobalServerOpenchain(t)233 // Start the HTTP REST test server234 httpServer := httptest.NewServer(buildOpenchainRESTRouter())235 defer httpServer.Close()236 body := performHTTPGet(t, httpServer.URL+"/transactions/NON-EXISTING-UUID")237 res := parseRESTResult(t, body)238 if res.Error == "" {239 t.Errorf("Expected an error when retrieving non-existing transaction, but got none")240 }241 block1, err := ledger.GetBlockByNumber(1)242 if err != nil {243 t.Fatalf("Can't fetch first block from ledger: %v", err)244 }245 firstTx := block1.Transactions[0]246 body1 := performHTTPGet(t, httpServer.URL+"/transactions/"+firstTx.Uuid)247 var tx1 protos.Transaction248 err = json.Unmarshal(body1, &tx1)249 if err != nil {250 t.Fatalf("Invalid JSON response: %v", err)251 }252 if tx1.Uuid != firstTx.Uuid {253 t.Errorf("Expected transaction uuid to be '%v' but got '%v'", firstTx.Uuid, tx1.Uuid)254 }255 if tx1.Timestamp.Seconds < startTime {256 t.Errorf("Expected transaction timestamp (%v) to be after the start time (%v)", tx1.Timestamp.Seconds, startTime)257 }258 badBody := performHTTPGet(t, httpServer.URL+"/transactions/with-\"-chars-in-the-URL")259 badRes := parseRESTResult(t, badBody)260 if badRes.Error == "" {261 t.Errorf("Expected a proper error when retrieving transaction with bad UUID")262 }263}264func TestServerOpenchainREST_API_Register(t *testing.T) {265 os.RemoveAll(getRESTFilePath())266 initGlobalServerOpenchain(t)267 // Start the HTTP REST test server268 httpServer := httptest.NewServer(buildOpenchainRESTRouter())269 defer httpServer.Close()270 expectError := func(reqBody string, expectedStatus int) {271 httpResponse, body := performHTTPPost(t, httpServer.URL+"/registrar", []byte(reqBody))272 if httpResponse.StatusCode != expectedStatus {273 t.Errorf("Expected an HTTP status code %#v but got %#v", expectedStatus, httpResponse.StatusCode)274 }275 res := parseRESTResult(t, body)276 if res.Error == "" {277 t.Errorf("Expected a proper error when registering")278 }279 }280 expectOK := func(reqBody string) {281 httpResponse, body := performHTTPPost(t, httpServer.URL+"/registrar", []byte(reqBody))282 if httpResponse.StatusCode != http.StatusOK {283 t.Errorf("Expected an HTTP status code %#v but got %#v", http.StatusOK, httpResponse.StatusCode)284 }285 res := parseRESTResult(t, body)286 if res.Error != "" {287 t.Errorf("Expected no error but got: %v", res.Error)288 }289 }290 expectError("", http.StatusBadRequest)291 expectError("} invalid json ]", http.StatusBadRequest)292 expectError(`{"enrollId":"user"}`, http.StatusBadRequest)293 expectError(`{"enrollId":"user","enrollSecret":"wrong_password"}`, http.StatusUnauthorized)294 expectOK(`{"enrollId":"user","enrollSecret":"password"}`)295 expectOK(`{"enrollId":"user","enrollSecret":"password"}`) // Already logged-in296}297func TestServerOpenchainREST_API_GetEnrollmentID(t *testing.T) {298 os.RemoveAll(getRESTFilePath())299 initGlobalServerOpenchain(t)300 // Start the HTTP REST test server301 httpServer := httptest.NewServer(buildOpenchainRESTRouter())302 defer httpServer.Close()303 body := performHTTPGet(t, httpServer.URL+"/registrar/NON_EXISTING_USER")304 res := parseRESTResult(t, body)305 if res.Error != "User NON_EXISTING_USER must log in." {306 t.Errorf("Expected an error when retrieving non-existing user, but got: %v", res.Error)307 }308 body = performHTTPGet(t, httpServer.URL+"/registrar/BAD-\"-CHARS")309 res = parseRESTResult(t, body)310 if res.Error != "Invalid enrollment ID parameter" {311 t.Errorf("Expected an error when retrieving non-existing user, but got: %v", res.Error)312 }313 // Login314 performHTTPPost(t, httpServer.URL+"/registrar", []byte(`{"enrollId":"myuser","enrollSecret":"password"}`))315 body = performHTTPGet(t, httpServer.URL+"/registrar/myuser")316 res = parseRESTResult(t, body)317 if res.OK == "" || res.Error != "" {318 t.Errorf("Expected no error when retrieving logged-in user, but got: %v", res.Error)319 }320}321func TestServerOpenchainREST_API_DeleteEnrollmentID(t *testing.T) {322 os.RemoveAll(getRESTFilePath())323 initGlobalServerOpenchain(t)324 // Start the HTTP REST test server325 httpServer := httptest.NewServer(buildOpenchainRESTRouter())326 defer httpServer.Close()327 body := performHTTPDelete(t, httpServer.URL+"/registrar/NON_EXISTING_USER")328 res := parseRESTResult(t, body)329 if res.OK == "" || res.Error != "" {330 t.Errorf("Expected no error when deleting non logged-in user, but got: %v", res.Error)331 }332 // Login333 performHTTPPost(t, httpServer.URL+"/registrar", []byte(`{"enrollId":"myuser","enrollSecret":"password"}`))334 body = performHTTPDelete(t, httpServer.URL+"/registrar/myuser")335 res = parseRESTResult(t, body)336 if res.OK == "" || res.Error != "" {337 t.Errorf("Expected no error when deleting a logged-in user, but got: %v", res.Error)338 }339}340func TestServerOpenchainREST_API_GetEnrollmentCert(t *testing.T) {341 os.RemoveAll(getRESTFilePath())342 initGlobalServerOpenchain(t)343 // Start the HTTP REST test server344 httpServer := httptest.NewServer(buildOpenchainRESTRouter())345 defer httpServer.Close()346 body := performHTTPGet(t, httpServer.URL+"/registrar/NON_EXISTING_USER/ecert")347 res := parseRESTResult(t, body)348 if res.Error == "" {349 t.Errorf("Expected an error when retrieving non-existing user, but got none")350 }351 body = performHTTPGet(t, httpServer.URL+"/registrar/BAD-\"-CHARS/ecert")352 res = parseRESTResult(t, body)353 if res.Error == "" {354 t.Errorf("Expected an error when retrieving non-existing user, but got none")355 }356}357func TestServerOpenchainREST_API_GetTransactionCert(t *testing.T) {358 os.RemoveAll(getRESTFilePath())359 initGlobalServerOpenchain(t)360 // Start the HTTP REST test server361 httpServer := httptest.NewServer(buildOpenchainRESTRouter())362 defer httpServer.Close()363 body := performHTTPGet(t, httpServer.URL+"/registrar/NON_EXISTING_USER/tcert")364 res := parseRESTResult(t, body)365 if res.Error == "" {366 t.Errorf("Expected an error when retrieving non-existing user, but got none")367 }368 body = performHTTPGet(t, httpServer.URL+"/registrar/BAD-\"-CHARS/tcert")369 res = parseRESTResult(t, body)370 if res.Error == "" {371 t.Errorf("Expected an error when retrieving non-existing user, but got none")372 }373}374func TestServerOpenchainREST_API_GetPeers(t *testing.T) {375 initGlobalServerOpenchain(t)376 // Start the HTTP REST test server377 httpServer := httptest.NewServer(buildOpenchainRESTRouter())378 defer httpServer.Close()379 body := performHTTPGet(t, httpServer.URL+"/network/peers")380 var msg protos.PeersMessage381 err := json.Unmarshal(body, &msg)382 if err != nil {383 t.Fatalf("Invalid JSON response: %v", err)384 }385 if len(msg.Peers) != 1 {386 t.Errorf("Expected a list of 1 peer but got %d peers", len(msg.Peers))387 }388 if msg.Peers[0].ID.Name != "jdoe" {389 t.Errorf("Expected a 'jdoe' peer but got '%s'", msg.Peers[0].ID.Name)390 }391}392func TestServerOpenchainREST_API_Chaincode_InvalidRequests(t *testing.T) {393 // Construct a ledger with 3 blocks.394 ledger := ledger.InitTestLedger(t)395 buildTestLedger1(ledger, t)396 initGlobalServerOpenchain(t)397 // Start the HTTP REST test server398 httpServer := httptest.NewServer(buildOpenchainRESTRouter())399 defer httpServer.Close()400 // Test empty POST payload401 httpResponse, body := performHTTPPost(t, httpServer.URL+"/chaincode", []byte{})402 if httpResponse.StatusCode != http.StatusBadRequest {403 t.Errorf("Expected an HTTP status code %#v but got %#v", http.StatusBadRequest, httpResponse.StatusCode)404 }405 res := parseRPCResponse(t, body)406 if res.Error == nil || res.Error.Code != InvalidRequest.Code {407 t.Errorf("Expected an error when sending empty payload, but got %#v", res.Error)408 }409 // Test invalid POST payload410 httpResponse, body = performHTTPPost(t, httpServer.URL+"/chaincode", []byte("{,,,"))411 if httpResponse.StatusCode != http.StatusBadRequest {412 t.Errorf("Expected an HTTP status code %#v but got %#v", http.StatusBadRequest, httpResponse.StatusCode)413 }414 res = parseRPCResponse(t, body)415 if res.Error == nil || res.Error.Code != ParseError.Code {416 t.Errorf("Expected an error when sending invalid JSON payload, but got %#v", res.Error)417 }418 // Test request without ID (=notification) results in no response419 httpResponse, body = performHTTPPost(t, httpServer.URL+"/chaincode", []byte(`{"jsonrpc":"2.0"}`))420 if httpResponse.StatusCode != http.StatusOK {421 t.Errorf("Expected an HTTP status code %#v but got %#v", http.StatusOK, httpResponse.StatusCode)422 }423 if len(body) != 0 {424 t.Errorf("Expected an empty response body to notification, but got %#v", string(body))425 }426 // Test missing JSON RPC version427 httpResponse, body = performHTTPPost(t, httpServer.URL+"/chaincode", []byte(`{"ID":123}`))428 if httpResponse.StatusCode != http.StatusBadRequest {429 t.Errorf("Expected an HTTP status code %#v but got %#v", http.StatusBadRequest, httpResponse.StatusCode)430 }431 res = parseRPCResponse(t, body)432 if res.Error == nil || res.Error.Code != InvalidRequest.Code {433 t.Errorf("Expected an error when sending missing jsonrpc version, but got %#v", res.Error)434 }435 // Test illegal JSON RPC version436 httpResponse, body = performHTTPPost(t, httpServer.URL+"/chaincode", []byte(`{"jsonrpc":"0.0","ID":123}`))437 if httpResponse.StatusCode != http.StatusBadRequest {438 t.Errorf("Expected an HTTP status code %#v but got %#v", http.StatusBadRequest, httpResponse.StatusCode)439 }440 res = parseRPCResponse(t, body)441 if res.Error == nil || res.Error.Code != InvalidRequest.Code {442 t.Errorf("Expected an error when sending illegal jsonrpc version, but got %#v", res.Error)443 }444 // Test missing JSON RPC method445 httpResponse, body = performHTTPPost(t, httpServer.URL+"/chaincode", []byte(`{"jsonrpc":"2.0","ID":123}`))446 if httpResponse.StatusCode != http.StatusBadRequest {447 t.Errorf("Expected an HTTP status code %#v but got %#v", http.StatusBadRequest, httpResponse.StatusCode)448 }449 res = parseRPCResponse(t, body)450 if res.Error == nil || res.Error.Code != InvalidRequest.Code {451 t.Errorf("Expected an error when sending missing jsonrpc method, but got %#v", res.Error)452 }453 // Test illegal JSON RPC method454 httpResponse, body = performHTTPPost(t, httpServer.URL+"/chaincode", []byte(`{"jsonrpc":"2.0","ID":123,"method":"non_existing"}`))455 if httpResponse.StatusCode != http.StatusNotFound {456 t.Errorf("Expected an HTTP status code %#v but got %#v", http.StatusNotFound, httpResponse.StatusCode)457 }458 res = parseRPCResponse(t, body)459 if res.Error == nil || res.Error.Code != MethodNotFound.Code {460 t.Errorf("Expected an error when sending illegal jsonrpc method, but got %#v", res.Error)461 }462}463func TestServerOpenchainREST_API_Chaincode_Deploy(t *testing.T) {464 // Construct a ledger with 3 blocks.465 ledger := ledger.InitTestLedger(t)466 buildTestLedger1(ledger, t)467 initGlobalServerOpenchain(t)468 // Start the HTTP REST test server469 httpServer := httptest.NewServer(buildOpenchainRESTRouter())470 defer httpServer.Close()471 // Test deploy without params472 httpResponse, body := performHTTPPost(t, httpServer.URL+"/chaincode", []byte(`{"jsonrpc":"2.0","ID":123,"method":"deploy"}`))473 if httpResponse.StatusCode != http.StatusBadRequest {474 t.Errorf("Expected an HTTP status code %#v but got %#v", http.StatusBadRequest, httpResponse.StatusCode)475 }476 res := parseRPCResponse(t, body)477 if res.Error == nil || res.Error.Code != InvalidParams.Code {478 t.Errorf("Expected an error when sending missing params, but got %#v", res.Error)479 }480 // Login481 performHTTPPost(t, httpServer.URL+"/registrar", []byte(`{"enrollId":"myuser","enrollSecret":"password"}`))482 // Test deploy with invalid chaincode path483 requestBody := `{484 "jsonrpc": "2.0",485 "ID": 123,486 "method": "deploy",487 "params": {488 "type": 1,489 "chaincodeID": {490 "path": "non-existing"491 },492 "ctorMsg": {493 "function": "Init",494 "args": []495 },496 "secureContext": "myuser"497 }498 }`499 httpResponse, body = performHTTPPost(t, httpServer.URL+"/chaincode", []byte(requestBody))500 if httpResponse.StatusCode != http.StatusOK {501 t.Errorf("Expected an HTTP status code %#v but got %#v", http.StatusOK, httpResponse.StatusCode)502 }503 res = parseRPCResponse(t, body)504 if res.Error == nil || res.Error.Code != ChaincodeDeployError.Code {505 t.Errorf("Expected an error when sending non-existing chaincode path, but got %#v", res.Error)506 }507 // Test deploy without username508 requestBody = `{509 "jsonrpc": "2.0",510 "ID": 123,511 "method": "deploy",512 "params": {513 "type": 1,514 "chaincodeID": {515 "path": "github.com/hyperledger/fabric/core/rest/test_chaincode"516 },517 "ctorMsg": {518 "function": "Init",519 "args": []520 }521 }522 }`523 httpResponse, body = performHTTPPost(t, httpServer.URL+"/chaincode", []byte(requestBody))524 res = parseRPCResponse(t, body)525 if res.Error == nil || res.Error.Code != InvalidParams.Code {526 t.Errorf("Expected an error when sending without username, but got %#v", res.Error)527 }528 // Test deploy with real chaincode path529 requestBody = `{530 "jsonrpc": "2.0",531 "ID": 123,532 "method": "deploy",533 "params": {534 "type": 1,535 "chaincodeID": {536 "path": "github.com/hyperledger/fabric/core/rest/test_chaincode"537 },538 "ctorMsg": {539 "function": "Init",540 "args": []541 },542 "secureContext": "myuser"543 }544 }`545 httpResponse, body = performHTTPPost(t, httpServer.URL+"/chaincode", []byte(requestBody))546 if httpResponse.StatusCode != http.StatusOK {547 t.Errorf("Expected an HTTP status code %#v but got %#v", http.StatusOK, httpResponse.StatusCode)548 }549 res = parseRPCResponse(t, body)550 if res.Error != nil {551 t.Errorf("Expected success but got %#v", res.Error)552 }553 if res.Result.Status != "OK" {554 t.Errorf("Expected OK but got %#v", res.Result.Status)555 }556 if res.Result.Message != "new_name_for_deployed_chaincode" {557 t.Errorf("Expected 'new_name_for_deployed_chaincode' but got '%#v'", res.Result.Message)558 }559}560func TestServerOpenchainREST_API_Chaincode_Invoke(t *testing.T) {561 // Construct a ledger with 3 blocks.562 ledger := ledger.InitTestLedger(t)563 buildTestLedger1(ledger, t)564 initGlobalServerOpenchain(t)565 // Start the HTTP REST test server566 httpServer := httptest.NewServer(buildOpenchainRESTRouter())567 defer httpServer.Close()568 // Test invoke without params569 httpResponse, body := performHTTPPost(t, httpServer.URL+"/chaincode", []byte(`{"jsonrpc":"2.0","ID":123,"method":"invoke"}`))570 if httpResponse.StatusCode != http.StatusBadRequest {571 t.Errorf("Expected an HTTP status code %#v but got %#v", http.StatusBadRequest, httpResponse.StatusCode)572 }573 res := parseRPCResponse(t, body)574 if res.Error == nil || res.Error.Code != InvalidParams.Code {575 t.Errorf("Expected an error when sending missing params, but got %#v", res.Error)576 }577 // Login578 performHTTPPost(t, httpServer.URL+"/registrar", []byte(`{"enrollId":"myuser","enrollSecret":"password"}`))579 // Test invoke with "fail" function580 httpResponse, body = performHTTPPost(t, httpServer.URL+"/chaincode", []byte(`{"jsonrpc":"2.0","ID":123,"method":"invoke","params":{"type":1,"chaincodeID":{"name":"dummy"},"ctorMsg":{"function":"fail","args":[]},"secureContext":"myuser"}}`))581 if httpResponse.StatusCode != http.StatusOK {582 t.Errorf("Expected an HTTP status code %#v but got %#v", http.StatusOK, httpResponse.StatusCode)583 }584 res = parseRPCResponse(t, body)585 if res.Error == nil || res.Error.Code != ChaincodeInvokeError.Code {586 t.Errorf("Expected an error when sending non-existing chaincode path, but got %#v", res.Error)587 }588 // Test invoke with "change_owner" function589 httpResponse, body = performHTTPPost(t, httpServer.URL+"/chaincode", []byte(`{"jsonrpc":"2.0","ID":123,"method":"invoke","params":{"type":1,"chaincodeID":{"name":"dummy"},"ctorMsg":{"function":"change_owner","args":[]},"secureContext":"myuser"}}`))590 if httpResponse.StatusCode != http.StatusOK {591 t.Errorf("Expected an HTTP status code %#v but got %#v", http.StatusOK, httpResponse.StatusCode)592 }593 res = parseRPCResponse(t, body)594 if res.Error != nil {595 t.Errorf("Expected success but got %#v", res.Error)596 }597 if res.Result.Status != "OK" {598 t.Errorf("Expected OK but got %#v", res.Result.Status)599 }600 if res.Result.Message != "change_owner_invoke_result" {601 t.Errorf("Expected 'change_owner_invoke_result' but got '%v'", res.Result.Message)602 }603}604func TestServerOpenchainREST_API_Chaincode_Query(t *testing.T) {605 // Construct a ledger with 3 blocks.606 ledger := ledger.InitTestLedger(t)607 buildTestLedger1(ledger, t)608 initGlobalServerOpenchain(t)609 // Start the HTTP REST test server610 httpServer := httptest.NewServer(buildOpenchainRESTRouter())611 defer httpServer.Close()612 // Test query without params613 httpResponse, body := performHTTPPost(t, httpServer.URL+"/chaincode", []byte(`{"jsonrpc":"2.0","ID":123,"method":"query"}`))614 if httpResponse.StatusCode != http.StatusBadRequest {615 t.Errorf("Expected an HTTP status code %#v but got %#v", http.StatusBadRequest, httpResponse.StatusCode)616 }617 res := parseRPCResponse(t, body)618 if res.Error == nil || res.Error.Code != InvalidParams.Code {619 t.Errorf("Expected an error when sending missing params, but got %#v", res.Error)620 }621 // Login622 performHTTPPost(t, httpServer.URL+"/registrar", []byte(`{"enrollId":"myuser","enrollSecret":"password"}`))623 // Test query with non-existing chaincode name624 httpResponse, body = performHTTPPost(t, httpServer.URL+"/chaincode", []byte(`{"jsonrpc":"2.0","ID":123,"method":"query","params":{"type":1,"chaincodeID":{"name":"non-existing"},"ctorMsg":{"function":"Init","args":[]},"secureContext":"myuser"}}`))625 if httpResponse.StatusCode != http.StatusOK {626 t.Errorf("Expected an HTTP status code %#v but got %#v", http.StatusOK, httpResponse.StatusCode)627 }628 res = parseRPCResponse(t, body)629 if res.Error == nil || res.Error.Code != ChaincodeQueryError.Code {630 t.Errorf("Expected an error when sending non-existing chaincode path, but got %#v", res.Error)631 }632 // Test query with fail function633 httpResponse, body = performHTTPPost(t, httpServer.URL+"/chaincode", []byte(`{"jsonrpc":"2.0","ID":123,"method":"query","params":{"type":1,"chaincodeID":{"name":"dummy"},"ctorMsg":{"function":"fail","args":[]},"secureContext":"myuser"}}`))634 if httpResponse.StatusCode != http.StatusOK {635 t.Errorf("Expected an HTTP status code %#v but got %#v", http.StatusOK, httpResponse.StatusCode)636 }637 res = parseRPCResponse(t, body)638 if res.Error == nil || res.Error.Code != ChaincodeQueryError.Code {639 t.Errorf("Expected an error when chaincode query fails, but got %#v", res.Error)640 }641 if res.Error.Data != "Error when querying chaincode: Query failure with special-\" chars" {642 t.Errorf("Expected an error message when chaincode query fails, but got %#v", res.Error.Data)643 }644 // Test query with get_owner function645 httpResponse, body = performHTTPPost(t, httpServer.URL+"/chaincode", []byte(`{"jsonrpc":"2.0","ID":123,"method":"query","params":{"type":1,"chaincodeID":{"name":"dummy"},"ctorMsg":{"function":"get_owner","args":[]},"secureContext":"myuser"}}`))646 if httpResponse.StatusCode != http.StatusOK {647 t.Errorf("Expected an HTTP status code %#v but got %#v", http.StatusOK, httpResponse.StatusCode)648 }649 res = parseRPCResponse(t, body)650 if res.Error != nil {651 t.Errorf("Expected success but got %#v", res.Error)652 }653 if res.Result.Status != "OK" {654 t.Errorf("Expected OK but got %#v", res.Result.Status)655 }656 if res.Result.Message != "get_owner_query_result" {657 t.Errorf("Expected 'get_owner_query_result' but got '%v'", res.Result.Message)658 }659}660func TestServerOpenchainREST_API_NotFound(t *testing.T) {661 httpServer := httptest.NewServer(buildOpenchainRESTRouter())662 defer httpServer.Close()663 body := performHTTPGet(t, httpServer.URL+"/non-existing")664 res := parseRESTResult(t, body)665 if res.Error != "Openchain endpoint not found." {666 t.Errorf("Expected an error when accessing non-existing endpoint, but got %#v", res.Error)667 }668}...
app-crm-handler.go
Source:app-crm-handler.go
...26// Handlers27func crmGetHandler(w http.ResponseWriter, r *http.Request) {28 crmModules, err := models.ListChildApplications(13)29 if err != nil {30 w.WriteHeader(http.StatusInternalServerError)31 w.Write([]byte("Error: 001, Internal Server Error"))32 return33 }34 visibleModules := 335 modules, err := models.ListApplications(visibleModules)36 if err != nil {37 w.WriteHeader(http.StatusInternalServerError)38 w.Write([]byte("Error: 001, Internal Server Error"))39 return40 }41 shortcuts, err := models.ListShortcuts()42 if err != nil {43 w.WriteHeader(http.StatusInternalServerError)44 w.Write([]byte("Error: 001, Internal Server Error"))45 return46 }47 utils.ExecuteTemplate(w, "mod-crm.html", struct {48 Title string49 Mods []models.Application50 CrmModules []models.Application51 Shortcuts []models.Shortcut52 }{53 Title: "Oswee Applications",54 Mods: modules,55 CrmModules: crmModules,56 Shortcuts: shortcuts,57 })58}59func crmDashboardGetHandler(w http.ResponseWriter, r *http.Request) {60 visibility := 161 applications, err := models.ListApplications(visibility)62 if err != nil {63 w.WriteHeader(http.StatusInternalServerError)64 w.Write([]byte("Error: 001, Internal Server Error"))65 return66 }67 visibleModules := 368 modules, err := models.ListApplications(visibleModules)69 if err != nil {70 w.WriteHeader(http.StatusInternalServerError)71 w.Write([]byte("Error: 001, Internal Server Error"))72 return73 }74 utils.ExecuteTemplate(w, "mod-crm-dashboard.html", struct {75 Title string76 Apps []models.Application77 Mods []models.Application78 }{79 Title: "Oswee.com: CRM Dashboard",80 Apps: applications,81 Mods: modules,82 })83}84func crmCustomersGetHandler(w http.ResponseWriter, r *http.Request) {85 visibleModules := 386 modules, err := models.ListApplications(visibleModules)87 if err != nil {88 w.WriteHeader(http.StatusInternalServerError)89 w.Write([]byte("Error: 001, Internal Server Error"))90 return91 }92 customers, err := models.ListCustomers()93 if err != nil {94 w.WriteHeader(http.StatusInternalServerError)95 w.Write([]byte("Error: 001, Internal Server Error"))96 return97 }98 shortcuts, err := models.ListShortcuts()99 if err != nil {100 w.WriteHeader(http.StatusInternalServerError)101 w.Write([]byte("Error: 001, Internal Server Error"))102 return103 }104 utils.ExecuteTemplate(w, "mod-crm-customers.html", struct {105 Title string106 Mods []models.Application107 Customers []models.Customer108 Shortcuts []models.Shortcut109 }{110 Title: "Oswee.com: CRM Customers",111 Mods: modules,112 Customers: customers,113 Shortcuts: shortcuts,114 })115}116func crmProjectsGetHandler(w http.ResponseWriter, r *http.Request) {117 visibleModules := 3118 modules, err := models.ListApplications(visibleModules)119 if err != nil {120 w.WriteHeader(http.StatusInternalServerError)121 w.Write([]byte("Error: 001, Internal Server Error"))122 return123 }124 projects, err := models.ListProjects()125 if err != nil {126 w.WriteHeader(http.StatusInternalServerError)127 w.Write([]byte("Error: 001, Internal Server Error"))128 return129 }130 shortcuts, err := models.ListShortcuts()131 if err != nil {132 w.WriteHeader(http.StatusInternalServerError)133 w.Write([]byte("Error: 001, Internal Server Error"))134 return135 }136 utils.ExecuteTemplate(w, "mod-crm-projects.html", struct {137 Title string138 Mods []models.Application139 Projects []models.Project140 Shortcuts []models.Shortcut141 }{142 Title: "Oswee.com: CRM Projects",143 Mods: modules,144 Projects: projects,145 Shortcuts: shortcuts,146 })147}148func crmCustomersNewHandler(w http.ResponseWriter, r *http.Request) {149 visibleModules := 3150 modules, err := models.ListApplications(visibleModules)151 if err != nil {152 w.WriteHeader(http.StatusInternalServerError)153 w.Write([]byte("Error: 001, Internal Server Error"))154 return155 }156 shortcuts, err := models.ListShortcuts()157 if err != nil {158 w.WriteHeader(http.StatusInternalServerError)159 w.Write([]byte("Error: 001, Internal Server Error"))160 return161 }162 utils.ExecuteTemplate(w, "mod-crm-customers-new.html", struct {163 Title string164 Customer models.Customer165 Mods []models.Application166 Projects []models.Project167 Shortcuts []models.Shortcut168 }{169 Title: "CRM Customers New",170 Mods: modules,171 Shortcuts: shortcuts,172 })173}174func crmCustomerCreateHandler(w http.ResponseWriter, r *http.Request) {175 err := r.ParseForm()176 if err != nil {177 log.Println(err.Error)178 }179 //name := r.PostForm.Get("account-name")180 accName := r.FormValue("account-name")181 // Database function goes there182 lastID, err := models.CustomerCreate(accName)183 fmt.Println("New customer created: ", lastID)184 http.Redirect(w, r, "/apps/crm/customers", 302)185}186func crmCustomerUpdateGetHandler(w http.ResponseWriter, r *http.Request) {187 vars := mux.Vars(r)188 customerID := vars["customerID"]189 customer := models.GetCustomer(customerID)190 visibleModules := 3191 modules, err := models.ListApplications(visibleModules)192 if err != nil {193 w.WriteHeader(http.StatusInternalServerError)194 w.Write([]byte("Error: 001, Internal Server Error"))195 return196 }197 shortcuts, err := models.ListShortcuts()198 if err != nil {199 w.WriteHeader(http.StatusInternalServerError)200 w.Write([]byte("Error: 001, Internal Server Error"))201 return202 }203 utils.ExecuteTemplate(w, "mod-crm-customers-update.html", struct {204 Title string205 Customer models.Customer206 Mods []models.Application207 Shortcuts []models.Shortcut208 }{209 Title: "CRM Customers New",210 Customer: customer,211 Mods: modules,212 Shortcuts: shortcuts,213 })214}215func crmCustomerUpdatePostHandler(w http.ResponseWriter, r *http.Request) {216 vars := mux.Vars(r)217 customerID := vars["customerID"]218 err := r.ParseForm()219 if err != nil {220 log.Println(err.Error)221 }222 accName := r.PostForm.Get("account-name")223 //accName := r.FormValue("account-name")224 // Database function goes there225 err = models.CustomerUpdate(accName, customerID)226 if err != nil {227 log.Println(err.Error)228 }229 fmt.Println("New customer updated: ")230 http.Redirect(w, r, "/apps/crm/customers", 302)231}232func crmCustomerDashboardGetHandler(w http.ResponseWriter, r *http.Request) {233 vars := mux.Vars(r)234 customerID := vars["customerID"]235 application := models.GetApplication(43) // Get CRM Customer Dashboard App236 customer := models.GetCustomer(customerID)237 visibleModules := 3238 modules, err := models.ListApplications(visibleModules)239 if err != nil {240 w.WriteHeader(http.StatusInternalServerError)241 w.Write([]byte("Error: 001, Internal Server Error"))242 return243 }244 tabs, err := models.ListChildApplications(15)245 if err != nil {246 w.WriteHeader(http.StatusInternalServerError)247 w.Write([]byte("Error: 001, Internal Server Error"))248 return249 }250 shortcuts, err := models.ListShortcuts()251 if err != nil {252 w.WriteHeader(http.StatusInternalServerError)253 w.Write([]byte("Error: 001, Internal Server Error"))254 return255 }256 utils.ExecuteTemplate(w, "mod-crm-customer.html", struct {257 Title string258 App models.Application259 Customer models.Customer260 Mods []models.Application261 Tabs []models.Application262 Shortcuts []models.Shortcut263 }{264 Title: "CRM Customer",265 App: application,266 Customer: customer,267 Mods: modules,268 Tabs: tabs,269 Shortcuts: shortcuts,270 })271}272func crmCustomerGetHandler(w http.ResponseWriter, r *http.Request) {273 vars := mux.Vars(r)274 customerID := vars["id"]275 application := models.GetApplication(15) // Get CRM App276 customer := models.GetCustomer(customerID)277 visibleModules := 3278 modules, err := models.ListApplications(visibleModules)279 if err != nil {280 w.WriteHeader(http.StatusInternalServerError)281 w.Write([]byte("Error: 001, Internal Server Error"))282 return283 }284 tabs, err := models.ListChildApplications(15)285 if err != nil {286 w.WriteHeader(http.StatusInternalServerError)287 w.Write([]byte("Error: 001, Internal Server Error"))288 return289 }290 shortcuts, err := models.ListShortcuts()291 if err != nil {292 w.WriteHeader(http.StatusInternalServerError)293 w.Write([]byte("Error: 001, Internal Server Error"))294 return295 }296 utils.ExecuteTemplate(w, "mod-crm-customer.html", struct {297 Title string298 App models.Application299 Customer models.Customer300 Mods []models.Application301 Tabs []models.Application302 Shortcuts []models.Shortcut303 }{304 Title: "CRM Customer",305 App: application,306 Customer: customer,307 Mods: modules,308 Tabs: tabs,309 Shortcuts: shortcuts,310 })311}312func crmCustomerProjectsGetHandler(w http.ResponseWriter, r *http.Request) {313 vars := mux.Vars(r)314 customerID := vars["customerID"]315 application := models.GetApplication(46) // Get CRM Customer Project316 customer := models.GetCustomer(customerID)317 visibleModules := 3318 modules, err := models.ListApplications(visibleModules)319 if err != nil {320 w.WriteHeader(http.StatusInternalServerError)321 w.Write([]byte("Error: 001, Internal Server Error"))322 return323 }324 tabs, err := models.ListChildApplications(15)325 if err != nil {326 w.WriteHeader(http.StatusInternalServerError)327 w.Write([]byte("Error: 001, Internal Server Error"))328 return329 }330 projects, err := models.ListCustomerProjects(customerID)331 if err != nil {332 w.WriteHeader(http.StatusInternalServerError)333 w.Write([]byte("Error: 001, Internal Server Error"))334 return335 }336 shortcuts, err := models.ListShortcuts()337 if err != nil {338 w.WriteHeader(http.StatusInternalServerError)339 w.Write([]byte("Error: 001, Internal Server Error"))340 return341 }342 utils.ExecuteTemplate(w, "mod-crm-customer.html", struct {343 Title string344 App models.Application345 Customer models.Customer346 Mods []models.Application347 Tabs []models.Application348 Projects []models.Project349 Shortcuts []models.Shortcut350 }{351 Title: "Oswee.com: CRM Projects",352 App: application,353 Customer: customer,354 Mods: modules,355 Tabs: tabs,356 Projects: projects,357 Shortcuts: shortcuts,358 })359}360func crmCustomerDeleteHandler(w http.ResponseWriter, r *http.Request) {361 vars := mux.Vars(r)362 customerID := vars["customerID"]363 err := models.CustomerDelete(customerID)364 if err != nil {365 log.Println(err.Error)366 }367 http.Redirect(w, r, "/apps/crm/customers", 302)368}369func crmCustomerProfileHandler(w http.ResponseWriter, r *http.Request) {370 vars := mux.Vars(r)371 customerID := vars["customerID"]372 customer := models.GetCustomer(customerID)373 visibleModules := 3374 modules, err := models.ListApplications(visibleModules)375 if err != nil {376 w.WriteHeader(http.StatusInternalServerError)377 w.Write([]byte("Error: 001, Internal Server Error"))378 return379 }380 shortcuts, err := models.ListShortcuts()381 if err != nil {382 w.WriteHeader(http.StatusInternalServerError)383 w.Write([]byte("Error: 001, Internal Server Error"))384 return385 }386 tabs, err := models.ListChildApplications(14)387 if err != nil {388 w.WriteHeader(http.StatusInternalServerError)389 w.Write([]byte("Error: 001, Internal Server Error"))390 return391 }392 utils.ExecuteTemplate(w, "mod-crm-customer-profile.html", struct {393 Title string394 Section string395 Customer models.Customer396 Mods []models.Application397 Shortcuts []models.Shortcut398 Tabs []models.Application399 }{400 Title: "CRM Customer Profile",401 Section: "customer-profile",402 Customer: customer,403 Mods: modules,...
AuthorService.go
Source:AuthorService.go
...18func (s *authorService) FetchAllAuthors(res http.ResponseWriter , req *http.Request){19 res.Header().Set("Content-Type", "application/json")20 authors, err := s.service.FetchAllAuthors()21 if(err != nil){22 http.Error(res, err.Error(), http.StatusInternalServerError)23 return24 }25 json.NewEncoder(res).Encode(authors)26}27func (s *authorService) FetchAuthorById(res http.ResponseWriter , req *http.Request){28 res.Header().Set("Content-Type", "application/json")29 req.ParseForm()30 id := req.FormValue("id")31 author, err := s.service.FetchAuthor(id)32 if(err != nil){33 if(err.Error() == "Blog does not exist"){34 http.Error(res, err.Error(), http.StatusNotFound)35 }else {36 http.Error(res, "", http.StatusInternalServerError)37 }38 return39 }40 json.NewEncoder(res).Encode(author)41}42func (s *authorService) UpdateAuthorPhoto(res http.ResponseWriter , req *http.Request) {43 var author = new(model.Author)44 err := json.NewDecoder(req.Body).Decode(&author)45 if(err != nil){46 http.Error(res,err.Error(), http.StatusBadRequest)47 return48 }49 updateError := s.service.UpdateAuthorPhoto(author)50 if(updateError != nil){51 if(updateError.Error() == "Author does not exist"){52 http.Error(res, err.Error(), http.StatusNotFound)53 }else {54 http.Error(res, "", http.StatusInternalServerError)55 }56 return57 }58}59func (s *authorService) UpdateAuthorUsername(res http.ResponseWriter , req *http.Request) {60 var author = new(model.Author)61 err := json.NewDecoder(req.Body).Decode(&author)62 if(err != nil){63 http.Error(res,err.Error(), http.StatusBadRequest)64 return65 }66 updateError := s.service.UpdateAuthorUsername(author)67 if(updateError != nil){68 if(updateError.Error() == "Author does not exist"){69 http.Error(res, updateError.Error(), http.StatusNotFound)70 }else {71 http.Error(res, "", http.StatusInternalServerError)72 }73 return74 }75}76func (s *authorService) RemoveAuthor(res http.ResponseWriter , req *http.Request) {77 req.ParseForm()78 id := req.FormValue("id")79 err := s.service.RemoveAuthor(id)80 if(err != nil){81 if(err.Error() == "Author does not exist"){82 http.Error(res, err.Error(), http.StatusNotFound)83 }else {84 http.Error(res, "", http.StatusInternalServerError)85 }86 return87 }88}89func (s *authorService) AddAuthor(res http.ResponseWriter , req *http.Request) {90 var author = new(model.Author)91 err := json.NewDecoder(req.Body).Decode(&author)92 if(err != nil){93 http.Error(res,err.Error(), http.StatusBadRequest)94 return95 }96 insertError := s.service.AddAuthor(author)97 if(insertError != nil){98 http.Error(res, err.Error(), http.StatusInternalServerError)99 return100 }101}...
Error
Using AI Code Generation
1import (2func main() {3 if err != nil {4 fmt.Println(err)5 }6 fmt.Println(res)7}
Error
Using AI Code Generation
1import (2func main() {3 if err != nil {4 fmt.Println(err)5 }6}
Error
Using AI Code Generation
1import (2func main() {3 if err != nil {4 fmt.Println(err)5 }6}
Error
Using AI Code Generation
1import (2func main() {3 if err != nil {4 fmt.Println("Error: ", err)5 }6 fmt.Println("Response: ", resp)7}
Error
Using AI Code Generation
1import (2func main() {3 http.HandleFunc("/", func(res http.ResponseWriter, req *http.Request) {4 fmt.Fprintln(res, "Hello World")5 })6 http.ListenAndServe(":8080", nil)7}
Error
Using AI Code Generation
1import (2func main() {3 fmt.Println(http.ErrAbortHandler)4 fmt.Println(http.ErrBodyNotAllowed)5 fmt.Println(http.ErrContentLength)6 fmt.Println(http.ErrHandlerTimeout)7 fmt.Println(http.ErrHeaderTooLong)8 fmt.Println(http.ErrMissingFile)9 fmt.Println(http.ErrMissingLocation)10 fmt.Println(http.ErrNoCookie)11 fmt.Println(http.ErrNotMultipart)12 fmt.Println(http.ErrNotSupported)13 fmt.Println(http.ErrShortBody)14 fmt.Println(http.ErrSkipAltProtocol)15 fmt.Println(http.ErrUseLastResponse)16}
Error
Using AI Code Generation
1import (2func main() {3 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {4 fmt.Println("Hello World")5 http.Error(w, "Error message", http.StatusMethodNotAllowed)6 })7 http.ListenAndServe(":8080", nil)8}
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!