Counting lines and words using Go
For those who need to count words and lines in text files, an easy approach for this matter is to use bufio.ScanWords and bufio.ScanLine in order to quickly solve the problem.
To count words:
input := "Spicy jalapeno pastrami ut ham turducken.\n Lorem sed ullamco, leberkas sint short loin strip steak ut shoulder shankle porchetta venison prosciutto turducken swine.\n Deserunt kevin frankfurter tongue aliqua incididunt tri-tip shank nostrud.\n" scanner := bufio.NewScanner(strings.NewReader(input)) // Set the split function for the scanning operation. scanner.Split(bufio.ScanWords) // Count the words. count := 0 for scanner.Scan() { count++ } if err := scanner.Err(); err != nil { fmt.Fprintln(os.Stderr, "reading input:", err) } fmt.Printf("%d\n", count)
ScanWords is a split function for a Scanner that returns each space-separated (checks unicode.IsSpace) word of text, with trimmed whitespace.
To count lines:
input := "Spicy jalapeno pastrami ut ham turducken.\n Lorem sed ullamco, leberkas sint short loin strip steak ut shoulder shankle porchetta venison prosciutto turducken swine.\n Deserunt kevin frankfurter tongue aliqua incididunt tri-tip shank nostrud.\n" scanner := bufio.NewScanner(strings.NewReader(input)) // Set the split function for the scanning operation. scanner.Split(bufio. ScanLines) // Count the lines. count := 0 for scanner.Scan() { count++ } if err := scanner.Err(); err != nil { fmt.Fprintln(os.Stderr, "reading input:", err) } fmt.Printf("%d\n", count)
ScanLines is a split function for a Scanner that returns each line of text (separated by "\r?\n"). It returns also empty lines and the last line is returned even if it has no newline at the end.
How To Mock Endpoints in Automated Acceptance Tests
The purpose of acceptance testing is to reproduce production environment as much as possible in order to evaluate the software in a 'real-world' situation similar to what the customers will experience and this includes using real endpoints.
But using real endpoints has some disadvantages. In automated acceptance tests, the endpoint will be stressed out and this is not performance testing. Also, you must use production data (even usernames and passwords) and this is not good because you might break something there. The list with the reasons could go on and on and this is why you should mock some endpoints in automated acceptance tests. Also, you should keep your endpoint's URL stored in environment variables to be able to change it easily (production URL or mock URL).
I will show you some basic examples of mocking endpoints written in Ruby, Python and GO.
Mock endpoint in Ruby
I have used Sinatra (DSL for quickly creating web applications in Ruby) which is very easy to use.
Install the gem:
gem install sinatra
#myapp.rb require ‘json’ require ‘sinatra’ get '/:username' do if params[:username] != 'your_username' status 404 else content_type :json {'message' => 'success'}.to_json end end
ruby myapp.rb -o 0.0.0.0 -p 5000 > /dev/null 2>&1 &
This will start the process in background and your endpoint on http://localhost:5000.
If you make a GET request on http://localhost:5000/your_username you will get a ‘success’ message, else a 404 status code.
Mock endpoint in Python
In Python it is very easy to create an endpoint with Flask.
To install it you have to run:
pip install flask-restful
#myapp.py #!flask/bin/python from flask import Flask, jsonify from flask import Response import json app = Flask(__name__) @app.route("/<username>", methods=['GET']) def put_username(username): if username == 'your_username': resp = Response("success!\n", mimetype='application/json') else: resp = Response("", status=404, mimetype='application/json') return resp if __name__ == '__main__': app.run(debug=True)
As you can see, this does the exact same thing as the endpoint created in Ruby.
You simply run it with
python myapp.py
Mock endpoint in GO
//myapp.go package main import ( "fmt" "net/http" "github.com/julienschmidt/httprouter" ) func username(w http.ResponseWriter, r *http.Request, p httprouter.Params) { if p.ByName("username") == "your_username" { w.Header().Set("Content-Type", "application/json") w.WriteHeader(200) fmt.Fprint(w, `{"message":"success"}`) } else { w.WriteHeader(404) } } func main() { r := httprouter.New() r.GET("/:username", username) http.ListenAndServe("localhost:5000", r) }
This does the same thing as the previous two endpoints and you run it with:
go run myapp.go
Thanks for reading this. What other ways of mocking an endpoint did you find?