Last active
November 27, 2020 09:24
-
-
Save fbiville/4d134e0f638b230e225494e2cbfb9021 to your computer and use it in GitHub Desktop.
Medium blog post - snippet 2
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
import ( | |
"github.com/neo4j-examples/golang-neo4j-realworld-example/pkg/users" | |
"github.com/neo4j/neo4j-go-driver/v4/neo4j" | |
. "github.com/onsi/ginkgo" | |
. "github.com/onsi/gomega" | |
"golang.org/x/crypto/bcrypt" | |
"io" | |
) | |
var driver neo4j.Driver | |
var repository users.UserRepository | |
var _ = Describe("User repository", func() { | |
BeforeEach(func() { | |
// [...] | |
driver, err = neo4j.NewDriver(address, neo4j.BasicAuth(username, password, "")) | |
Expect(err).To(BeNil(), "Driver should be created") | |
repository = &users.UserNeo4jRepository{Driver: driver} | |
}) | |
It("logs users in", func() { | |
session := driver.NewSession(neo4j.SessionConfig{}) | |
defer Close(session, "Session") // Close is a function that close any io.Closer | |
// transaction functions can be retried upon failure, use them! :) | |
_, err := session.WriteTransaction(func(tx neo4j.Transaction) (interface{}, error) { | |
_, err := tx.Run( | |
`CREATE (:User {username: "flo", email: $email, password: $password})`, // insert user | |
map[string]interface{}{ // set query parameters | |
"email": "florent@example.org", | |
"password": hash("sup3rpassw0rd"), // computes a bcrypt hash | |
}) | |
return nil, err | |
}) | |
Expect(err).To(BeNil(), "user should be inserted") | |
user, err := repository.FindByEmailAndPassword("florent@example.org", "sup3rpassw0rd") | |
// [...] test expectations | |
}) | |
}) | |
func Close(closer io.Closer, resourceName string) { | |
Expect(closer.Close()). | |
To(BeNil(), "%s should close", resourceName) | |
} | |
func hash(password string) string { | |
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) | |
Expect(err).To(BeNil(), "password should be hashed") | |
return string(hashedPassword) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment