<commit_before>package useractions

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"net/url"
	"strings"
	"testing"

	"github.com/fragmenta/auth"
	"github.com/fragmenta/mux"
	"github.com/fragmenta/query"

	"github.com/kennygrant/gohackernews/src/lib/resource"
	"github.com/kennygrant/gohackernews/src/users"
)

// names is used to test setting and getting the first string field of the user.
var names = []string{"admin", "bar"}

// testSetup performs setup for integration tests
// using the test database, real views, and mock authorisation
// If we can run this once for global tests it might be more efficient?
func TestSetup(t *testing.T) {
	err := resource.SetupTestDatabase(3)
	if err != nil {
		fmt.Printf("users: Setup db failed %s", err)
	}

	// Set up mock auth
	resource.SetupAuthorisation()

	// Load templates for rendering
	resource.SetupView(3)

	router := mux.New()
	mux.SetDefault(router)

	// FIXME - Need to write routes out here again, but without pkg prefix
	// Any neat way to do this instead? We'd need a separate routes package under app...
	router.Add("/users", nil)
	router.Add("/users/create", nil)
	router.Add("/users/create", nil).Post()
	router.Add("/users/login", nil)
	router.Add("/users/login", nil).Post()
	router.Add("/users/login", nil).Post()
	router.Add("/users/logout", nil).Post()
	router.Add("/users/{id:\\d+}/update", nil)
	router.Add("/users/{id:\\d+}/update", nil).Post()
	router.Add("/users/{id:\\d+}/destroy", nil).Post()
	router.Add("/users/{id:\\d+}", nil)

	// Delete all users to ensure we get consistent results?
	_, err = query.ExecSQL("delete from users;")
	if err != nil {
		t.Fatalf("error setting up:%s", err)
	}
	// Insert a test admin user for checking logins - never delete as will
	// be required for other resources testing
	_, err = query.ExecSQL("INSERT INTO users (id,email,name,status,role,password_hash) VALUES(1,'<EMAIL>','admin',100,100,'$2a$10$2IUzpI/yH0Xc.qs9Z5UUL.3f9bqi0ThvbKs6Q91UOlyCEGY8hdBw6');")
	if err != nil {
		t.Fatalf("error setting up:%s", err)
	}
	// Insert user to delete
	_, err = query.ExecSQL("INSERT INTO users (id,email,name,status,role,password_hash) VALUES(2,'<EMAIL>','<PASSWORD>',100,0,'$2a$10$2IUzpI/yH0Xc.qs9Z5UUL.3f9bqi0ThvbKs6Q91UOlyCEGY8hdBw6');")
	if err != nil {
		t.Fatalf("error setting up:%s", err)
	}

	query.ExecSQL("ALTER SEQUENCE users_id_seq RESTART WITH 1;")
}

// Test GET /users/create
func TestShowCreateUsers(t *testing.T) {

	// Setup request and recorder
	r := httptest.NewRequest("GET", "/users/create", nil)
	w := httptest.NewRecorder()

	// Set up user session cookie for ANON user
	err := resource.AddUserSessionCookie(w, r, 0)
	if err != nil {
		t.Fatalf("useractions: error setting session %s", err)
	}

	// Run the handler
	err = HandleCreateShow(w, r)

	// Test the error response
	if err != nil || w.Code != http.StatusOK {
		t.Fatalf("useractions: error handling HandleCreateShow %s %d", err, w.Code)
	}

	// Test the body for a known pattern
	pattern := "resource-update-form"
	if !strings.Contains(w.Body.String(), pattern) {
		t.Fatalf("useractions: unexpected response for HandleCreateShow expected:%s got:%s", pattern, w.Body.String())
	}

}

// Test POST /users/create
func TestCreateUsers(t *testing.T) {

	form := url.Values{}
	form.Add("name", names[0])
	body := strings.NewReader(form.Encode())

	r := httptest.NewRequest("POST", "/users/create", body)
	r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
	w := httptest.NewRecorder()

	// Set up user session cookie for ANON user
	err := resource.AddUserSessionCookie(w, r, 0)
	if err != nil {
		t.Fatalf("useractions: error setting session %s", err)
	}

	// Run the handler to update the user
	err = HandleCreate(w, r)
	if err != nil {
		t.Fatalf("useractions: error handling HandleCreate %s", err)
	}

	// Test we get a redirect after update (to the user concerned)
	if w.Code != http.StatusFound {
		t.Fatalf("useractions: unexpected response code for HandleCreate expected:%d got:%d", http.StatusFound, w.Code)
	}

	// Check the user name is in now value names[1]<commit_msg>Fix failing user test due to password check<commit_after>package useractions

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"net/url"
	"strings"
	"testing"

	"github.com/fragmenta/auth"
	"github.com/fragmenta/mux"
	"github.com/fragmenta/query"

	"github.com/kennygrant/gohackernews/src/lib/resource"
	"github.com/kennygrant/gohackernews/src/users"
)

// names is used to test setting and getting the first string field of the user.
var names = []string{"admin", "bar"}

// testSetup performs setup for integration tests
// using the test database, real views, and mock authorisation
// If we can run this once for global tests it might be more efficient?
func TestSetup(t *testing.T) {
	err := resource.SetupTestDatabase(3)
	if err != nil {
		fmt.Printf("users: Setup db failed %s", err)
	}

	// Set up mock auth
	resource.SetupAuthorisation()

	// Load templates for rendering
	resource.SetupView(3)

	router := mux.New()
	mux.SetDefault(router)

	// FIXME - Need to write routes out here again, but without pkg prefix
	// Any neat way to do this instead? We'd need a separate routes package under app...
	router.Add("/users", nil)
	router.Add("/users/create", nil)
	router.Add("/users/create", nil).Post()
	router.Add("/users/login", nil)
	router.Add("/users/login", nil).Post()
	router.Add("/users/login", nil).Post()
	router.Add("/users/logout", nil).Post()
	router.Add("/users/{id:\\d+}/update", nil)
	router.Add("/users/{id:\\d+}/update", nil).Post()
	router.Add("/users/{id:\\d+}/destroy", nil).Post()
	router.Add("/users/{id:\\d+}", nil)

	// Delete all users to ensure we get consistent results?
	_, err = query.ExecSQL("delete from users;")
	if err != nil {
		t.Fatalf("error setting up:%s", err)
	}
	// Insert a test admin user for checking logins - never delete as will
	// be required for other resources testing
	_, err = query.ExecSQL("INSERT INTO users (id,email,name,status,role,password_hash) VALUES(1,'<EMAIL>','admin',100,100,'$2a$10$2IUzpI/yH0Xc.qs9Z5UUL.3f9bqi0ThvbKs6Q91UOlyCEGY8hdBw6');")
	if err != nil {
		t.Fatalf("error setting up:%s", err)
	}
	// Insert user to delete
	_, err = query.ExecSQL("INSERT INTO users (id,email,name,status,role,password_hash) VALUES(2,'<EMAIL>','test',100,0,'$2a$10$2IUzpI/yH0Xc.qs9Z5UUL.3f9bqi0ThvbKs6Q91UOlyCEGY8hdBw6');")
	if err != nil {
		t.Fatalf("error setting up:%s", err)
	}

	query.ExecSQL("ALTER SEQUENCE users_id_seq RESTART WITH 1;")
}

// Test GET /users/create
func TestShowCreateUsers(t *testing.T) {

	// Setup request and recorder
	r := httptest.NewRequest("GET", "/users/create", nil)
	w := httptest.NewRecorder()

	// Set up user session cookie for ANON user
	err := resource.AddUserSessionCookie(w, r, 0)
	if err != nil {
		t.Fatalf("useractions: error setting session %s", err)
	}

	// Run the handler
	err = HandleCreateShow(w, r)

	// Test the error response
	if err != nil || w.Code != http.StatusOK {
		t.Fatalf("useractions: error handling HandleCreateShow %s %d", err, w.Code)
	}

	// Test the body for a known pattern
	pattern := "resource-update-form"
	if !strings.Contains(w.Body.String(), pattern) {
		t.Fatalf("useractions: unexpected response for HandleCreateShow expected:%s got:%s", pattern, w.Body.String())
	}

}

// Test POST /users/create
func TestCreateUsers(t *testing.T) {

	form := url.Values{}
	form.Add("name", names[0])
	form.Add("password", "<PASSWORD>") // required pass length
	body := strings.NewReader(form.Encode())

	r := httptest.NewRequest("POST", "/users/create", body)
	r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
	w := httptest.NewRecorder()

	// Set up user session cookie for ANON user
	err := resource.AddUserSessionCookie(w, r, 0)
	if err != nil {
		t.Fatalf("useractions: error setting session %s", err)
	}

	// Run the handler to update the user
	err = HandleCreate(w, r)
	if err != nil {
		t.Fatalf("useractions: error handling HandleCreate %s", err)
	}

	// Test we get a redirect after update (to the user concerned)
	if w.Code != http.StatusFound {
		t.Fatalf("useractions: unexpected response code for HandleCreate expected:%d got:%d", http.StatusFound, w.Code)
	}

	// Check the user name is in now value names[1]
{'fraction_non_alphanumeric': 0.15515151515151515, 'fraction_numerical': 0.01187878787878788, 'mean_word_length': 4.189308176100629, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5505349', 'n_tokens_mistral': 2957, 'n_tokens_neox': 2858, 'n_words': 783}