Last active
March 9, 2022 09:45
-
-
Save earlonrails/955b174fd394d631b425 to your computer and use it in GitHub Desktop.
Mock neo4j/neoism connection in go for testing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package testhelpers | |
import ( | |
"fmt" | |
"net/http" | |
"net/http/httptest" | |
"net/url" | |
"github.com/jmcvetta/neoism" | |
) | |
func MockHttpServer(serverMuxer http.Handler) (*httptest.Server, *http.Client) { | |
server := httptest.NewServer(serverMuxer) | |
tr := &http.Transport{ | |
Proxy: func(req *http.Request) (*url.URL, error) { | |
return url.Parse(server.URL) | |
}, | |
} | |
httpClient := &http.Client{Transport: tr} | |
return server, httpClient | |
} | |
func MockDatabase(code int, body string) (*httptest.Server, *neoism.Database) { | |
// first get a valid neo4j db instance | |
mux := http.NewServeMux() | |
connBody := "" | |
mux.Handle("/db/data/", | |
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
w.WriteHeader(200) | |
w.Header().Set("Content-Type", "application/json") | |
fmt.Fprintln(w, | |
connBody, | |
) | |
}), | |
) | |
mux.Handle("/db/data/cypher", | |
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
w.WriteHeader(code) | |
w.Header().Set("Content-Type", "application/json") | |
fmt.Fprintln(w, body) | |
}), | |
) | |
server, _ := MockHttpServer(mux) | |
connBody = fmt.Sprintf(`{ | |
"extensions" : { }, | |
"node" : "%[1]v/db/data/node", | |
"node_index" : "%[1]v/db/data/index/node", | |
"relationship_index" : "%[1]v/db/data/index/relationship", | |
"extensions_info" : "%[1]v/db/data/ext", | |
"relationship_types" : "%[1]v/db/data/relationship/types", | |
"batch" : "%[1]v/db/data/batch", | |
"cypher" : "%[1]v/db/data/cypher", | |
"indexes" : "%[1]v/db/data/schema/index", | |
"constraints" : "%[1]v/db/data/schema/constraint", | |
"transaction" : "%[1]v/db/data/transaction", | |
"node_labels" : "%[1]v/db/data/labels", | |
"neo4j_version" : "2.2.1" | |
}`, | |
server.URL, | |
) | |
db, _ := neoism.Connect(server.URL + "/db/data/") | |
// now create the mock for the data you would like to return | |
return server, db | |
} | |
// Example usage: | |
// server, db := testhelpers.MockDatabase(200, | |
// `{ | |
// "columns" : [ "follower", "followee", "created_at" ], | |
// "data" : [ [ "7f701339-bd59-4739-8e5b-xxxxxx", "03q234ad-7d03-46f5-97b5-xxxxxxxx", 22222 ] ] | |
// }`, | |
// ) | |
// defer server.Close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment