<commit_before>/*
 * EliasDB
 *
 * Copyright 2016 <NAME>. All rights reserved.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

package main

import (
	"errors"
	"flag"
	"fmt"
	"log"
	"net/http"
	"os"
	"strings"
	"testing"
	"time"

	"devt.de/common/fileutil"
	"devt.de/common/httputil"
	"devt.de/eliasdb/api"
	"devt.de/eliasdb/graph/graphstorage"
)

const testdb = "testdb"

const invalidFileName = "**" + string(0x0)

var printLog = []string{}
var errorLog = []string{}

var printLogging = false

func TestMain(m *testing.M) {
	flag.Parse()

	basepath = testdb + "/"

	// Log all print and error messagesí

	print = func(v ...interface{}) {
		if printLogging {
			fmt.Println(v...)
		}
		printLog = append(printLog, fmt.Sprint(v...))
	}
	fatal = func(v ...interface{}) {
		if printLogging {
			fmt.Println(v...)
		}
		errorLog = append(errorLog, fmt.Sprint(v...))
	}

	defer func() {
		fatal = log.Fatal
		basepath = ""
	}()

	if res, _ := fileutil.PathExists(testdb); res {
		if err := os.RemoveAll(testdb); err != nil {
			fmt.Print("Could not remove test directory:", err.Error())
		}
	}

	ensurePath(testdb)

	// Run the tests

	res := m.Run()

	if res, _ := fileutil.PathExists(testdb); res {
		if err := os.RemoveAll(testdb); err != nil {
			fmt.Print("Could not remove test directory:", err.Error())
		}
	}

	os.Exit(res)
}

func TestMainNormalCase(t *testing.T) {

	// Make sure to reset the DefaultServeMux

	defer func() { http.DefaultServeMux = http.NewServeMux() }()

	// Make sure to remove any files

	defer func() {
		if err := os.RemoveAll(testdb); err != nil {
			fmt.Print("Could not remove test directory:", err.Error())
		}
		time.Sleep(time.Duration(100) * time.Millisecond)
		ensurePath(testdb)
	}()

	// Reset logs

	printLog = []string{}
	errorLog = []string{}

	errorChan := make(chan error)

	// Test handle function

	api.HandleFunc = func(pattern string, handler func(http.ResponseWriter, *http.Request)) {
		defer func() {
			if r := recover(); r == nil {
				t.Error("Request with nil request and nil response should cause a panic.")
			}
		}()
		handler(nil, nil)
	}

	// Kick off main function

	go func() {
		main()
		errorChan <- nil
	}()

	// To exit the main function the lock watcher thread
	// has to recognise that the lockfile was modified

	time.Sleep(time.Duration(2) * time.Second)

	// Do a normal shutdown with a log file

	if err := shutdownWithLogFile(); err != nil {
		t.Error(err)
		return
	}

	// Wait for the main function to end

	if err := <-errorChan; err != nil || len(errorLog) != 0 {
		t.Error("Unexpected ending of main thread:", err, errorLog)
		return
	}

	// Check the print log

	if logString := strings.Join(printLog, "\n"); logString != `
EliasDB 0.8
Starting datastore in testdb/db
Creating GraphManager instance
Creating key (key.pem) and certificate (cert.pem) in: ssl
Ensuring web folder: testdb/web
Ensuring web termminal: testdb/web/db/term.html
Starting server on: localhost:9090
Writing fingerprint file: testdb/web/fingerprint.json
Waiting for shutdown
Lockfile was modified
Shutting down
Closing datastore`[1:] {
		t.Error("Unexpected log:", logString)
		return
	}

}<commit_msg>Adding rev output in test<commit_after>/*
 * EliasDB
 *
 * Copyright 2016 <NAME>. All rights reserved.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

package main

import (
	"errors"
	"flag"
	"fmt"
	"log"
	"net/http"
	"os"
	"strings"
	"testing"
	"time"

	"devt.de/common/fileutil"
	"devt.de/common/httputil"
	"devt.de/eliasdb/api"
	"devt.de/eliasdb/graph/graphstorage"
)

const testdb = "testdb"

const invalidFileName = "**" + string(0x0)

var printLog = []string{}
var errorLog = []string{}

var printLogging = false

func TestMain(m *testing.M) {
	flag.Parse()

	basepath = testdb + "/"

	// Log all print and error messagesí

	print = func(v ...interface{}) {
		if printLogging {
			fmt.Println(v...)
		}
		printLog = append(printLog, fmt.Sprint(v...))
	}
	fatal = func(v ...interface{}) {
		if printLogging {
			fmt.Println(v...)
		}
		errorLog = append(errorLog, fmt.Sprint(v...))
	}

	defer func() {
		fatal = log.Fatal
		basepath = ""
	}()

	if res, _ := fileutil.PathExists(testdb); res {
		if err := os.RemoveAll(testdb); err != nil {
			fmt.Print("Could not remove test directory:", err.Error())
		}
	}

	ensurePath(testdb)

	// Run the tests

	res := m.Run()

	if res, _ := fileutil.PathExists(testdb); res {
		if err := os.RemoveAll(testdb); err != nil {
			fmt.Print("Could not remove test directory:", err.Error())
		}
	}

	os.Exit(res)
}

func TestMainNormalCase(t *testing.T) {

	// Make sure to reset the DefaultServeMux

	defer func() { http.DefaultServeMux = http.NewServeMux() }()

	// Make sure to remove any files

	defer func() {
		if err := os.RemoveAll(testdb); err != nil {
			fmt.Print("Could not remove test directory:", err.Error())
		}
		time.Sleep(time.Duration(100) * time.Millisecond)
		ensurePath(testdb)
	}()

	// Reset logs

	printLog = []string{}
	errorLog = []string{}

	errorChan := make(chan error)

	// Test handle function

	api.HandleFunc = func(pattern string, handler func(http.ResponseWriter, *http.Request)) {
		defer func() {
			if r := recover(); r == nil {
				t.Error("Request with nil request and nil response should cause a panic.")
			}
		}()
		handler(nil, nil)
	}

	// Kick off main function

	go func() {
		main()
		errorChan <- nil
	}()

	// To exit the main function the lock watcher thread
	// has to recognise that the lockfile was modified

	time.Sleep(time.Duration(2) * time.Second)

	// Do a normal shutdown with a log file

	if err := shutdownWithLogFile(); err != nil {
		t.Error(err)
		return
	}

	// Wait for the main function to end

	if err := <-errorChan; err != nil || len(errorLog) != 0 {
		t.Error("Unexpected ending of main thread:", err, errorLog)
		return
	}

	// Check the print log

	if logString := strings.Join(printLog, "\n"); logString != `
EliasDB 0.8.0
Starting datastore in testdb/db
Creating GraphManager instance
Creating key (key.pem) and certificate (cert.pem) in: ssl
Ensuring web folder: testdb/web
Ensuring web termminal: testdb/web/db/term.html
Starting server on: localhost:9090
Writing fingerprint file: testdb/web/fingerprint.json
Waiting for shutdown
Lockfile was modified
Shutting down
Closing datastore`[1:] {
		t.Error("Unexpected log:", logString)
		return
	}

}
{'fraction_non_alphanumeric': 0.14283564118001205, 'fraction_numerical': 0.006773028296207104, 'mean_word_length': 3.3717105263157894, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, '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': '3380812', 'n_tokens_mistral': 2526, 'n_tokens_neox': 2297, 'n_words': 682}