aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


server/admin_fixture_test.go (1989B)


      1 package main
      2 
      3 import (
      4 	"fmt"
      5 	"net/http"
      6 	"net/http/httptest"
      7 	"strings"
      8 )
      9 
     10 // State-transition tests exercise handlers beneath the authentication boundary.
     11 // Admin authentication tests use httpHandler directly.
     12 func serveAdminTestRequest(world *server, w http.ResponseWriter, r *http.Request) {
     13 	if r.Method == "POST" && r.URL.Path == "/admin/players" {
     14 		world.createUser(w, r)
     15 		return
     16 	}
     17 	path := strings.TrimPrefix(r.URL.Path, strings.TrimSuffix(world.baseURL, "/"))
     18 	if path == "/admin" || strings.HasPrefix(path, "/admin/") {
     19 		http.StripPrefix(strings.TrimSuffix(world.baseURL, "/"), world.adminHandler()).ServeHTTP(w, r)
     20 		return
     21 	}
     22 	world.httpHandler().ServeHTTP(w, r)
     23 }
     24 
     25 func adminTestHandler(world *server) http.Handler {
     26 	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { serveAdminTestRequest(world, w, r) })
     27 }
     28 
     29 func adminRequest(handler http.Handler, method, path, body string, cookie *http.Cookie) *httptest.ResponseRecorder {
     30 	request := httptest.NewRequest(method, path, strings.NewReader(body))
     31 	request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
     32 	if cookie != nil {
     33 		request.AddCookie(cookie)
     34 	}
     35 	response := httptest.NewRecorder()
     36 	handler.ServeHTTP(response, request)
     37 	return response
     38 }
     39 
     40 // Create isolated characters for persistence and editor tests.
     41 func (server *server) createUser(w http.ResponseWriter, r *http.Request) {
     42 	name := strings.TrimSpace(r.FormValue("name"))
     43 	player := server.newCharacter()
     44 	player.name = name
     45 	if err := player.userData().validate(); err != nil {
     46 		delete(server.characters, player.id)
     47 		server.nextCharacter--
     48 		http.Error(w, err.Error(), http.StatusBadRequest)
     49 		return
     50 	}
     51 	err := server.saveUser(player)
     52 	if err != nil {
     53 		delete(server.characters, player.id)
     54 		server.nextCharacter--
     55 	}
     56 	if err != nil {
     57 		http.Error(w, err.Error(), http.StatusInternalServerError)
     58 		return
     59 	}
     60 	http.Redirect(w, r, fmt.Sprintf("%sadmin/players/%d", server.baseURL, player.id), http.StatusSeeOther)
     61 }