github.com/bitcubate/cryptojournal@v1.2.5-0.20171102134152-f578b3d788ab/src/lib/resource/testing.go (about) 1 package resource 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "io/ioutil" 7 "net/http" 8 "net/http/httptest" 9 "path/filepath" 10 "strings" 11 12 "github.com/fragmenta/auth" 13 "github.com/fragmenta/auth/can" 14 "github.com/fragmenta/query" 15 "github.com/fragmenta/server/log" 16 "github.com/fragmenta/view" 17 18 "github.com/bitcubate/cryptojournal/src/lib/helpers" 19 ) 20 21 // This file contains some test helpers for resources. 22 23 // basePath returns the path to the fragmenta root from a given test folder. 24 func basePath(depth int) string { 25 // Construct a path to root 26 p := "" 27 for i := 0; i < depth; i++ { 28 p = filepath.Join(p, "..") 29 } 30 return p 31 } 32 33 // SetupAuthorisation sets up mock authorisation. 34 func SetupAuthorisation() { 35 36 // Setup the auth library 37 var testKey = "12353bce2bbc4efb90eff81c29dc982de9a0176b568db18a61b4f4732cadabbc" 38 39 // Setup auth with some test values - could read these from config I guess 40 auth.HMACKey = auth.HexToBytes(testKey) 41 auth.SecretKey = auth.HexToBytes(testKey) 42 auth.SessionName = "test_session" 43 44 // Set up admin permissions for testing - 45 // hard coded role to avoid cyclic dependency 46 can.Authorise(100, can.ManageResource, can.Anything) 47 48 // Readers may edit their user 49 can.AuthoriseOwner(10, can.UpdateResource, "users") 50 51 // Anon may create users 52 can.AuthoriseOwner(0, can.CreateResource, "users") 53 54 } 55 56 // AddUserSessionCookie adds a new cookie for the given user 57 // on the incoming request, so that we can test authentication in handlers. 58 func AddUserSessionCookie(w *httptest.ResponseRecorder, r *http.Request, id int) error { 59 60 // Build the session from the secure cookie, or create a new one 61 session, err := auth.Session(w, r) 62 if err != nil { 63 return err 64 } 65 66 secret := auth.BytesToBase64(auth.RandomToken(auth.TokenLength)) 67 session.Set(auth.SessionTokenKey, secret) 68 69 // Now from secret, generate a secure token for this request 70 token := auth.BytesToBase64(auth.AuthenticityTokenWithSecret(auth.Base64ToBytes(secret))) 71 72 // Write value of user id 73 session.Set(auth.SessionUserKey, fmt.Sprintf("%d", id)) 74 75 // Set the cookie on the recorder 76 err = session.Save(w) 77 if err != nil { 78 return err 79 } 80 81 // Set the auth token on params of request 82 // Cheat and set on raw query, which we don't use in tests 83 urlQ := fmt.Sprintf("authenticity_token=%s", token) 84 r.URL.RawQuery = urlQ 85 86 // Now get the entire cookie back out 87 // and put it on the request as if it were coming in from browser 88 r.Header.Set("Cookie", strings.Join(w.HeaderMap["Set-Cookie"], "")) 89 90 // Perform an authenticity check: 91 err = auth.CheckAuthenticityToken(token, r) 92 if err != nil { 93 return err 94 } 95 96 return nil 97 } 98 99 // SetupView sets up the view package for testing by loading templates. 100 func SetupView(depth int) error { 101 view.Production = false 102 103 // A very limited translation - would prefer to use editable.js 104 // instead and offer proper editing TODO: move to editable.js instead 105 view.Helpers["markup"] = helpers.Markup 106 view.Helpers["timeago"] = helpers.TimeAgo 107 view.Helpers["root_url"] = helpers.RootURL 108 109 return view.LoadTemplatesAtPaths([]string{filepath.Join(basePath(depth), "src")}, view.Helpers) 110 } 111 112 // SetupTestDatabase sets up the database for all tests from the test config. 113 func SetupTestDatabase(depth int) error { 114 115 // Set up a stderr logger with time prefix 116 logger, err := log.NewStdErr(log.PrefixDateTime) 117 if err != nil { 118 return err 119 } 120 log.Add(logger) 121 122 // Read config json 123 path := filepath.Join(basePath(depth), "secrets", "fragmenta.json") 124 file, err := ioutil.ReadFile(path) 125 if err != nil { 126 return err 127 } 128 129 var data map[string]map[string]string 130 err = json.Unmarshal(file, &data) 131 if err != nil { 132 return err 133 } 134 135 config := data["test"] 136 options := map[string]string{ 137 "adapter": config["db_adapter"], 138 "user": config["db_user"], 139 "password": config["db_pass"], 140 "db": config["db"], 141 } 142 143 // Ask query to open the database 144 err = query.OpenDatabase(options) 145 if err != nil { 146 return err 147 } 148 149 // For speed 150 query.Exec("set synchronous_commit=off;") 151 return nil 152 }