text:
package gosqs

import (
	"context"
	"encoding/xml"
	"net/http"
	"net/http/httptest"
	"net/url"
	"reflect"
	"strings"
	"sync"
	"testing"
	"time"

	"github.com/p4tin/goaws/app"
)

func TestListQueues_POST_NoQueues(t *testing.T) {
	// Create a request to pass to our handler. We don't have any query parameters for now, so we'll
	// pass 'nil' as the third parameter.
	req, err := http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	// We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response.
	rr := httptest.NewRecorder()
	handler := http.HandlerFunc(ListQueues)

	// Our handlers satisfy http.Handler, so we can call their ServeHTTP method
	// directly and pass in our Request and ResponseRecorder.
	handler.ServeHTTP(rr, req)

	// Check the status code is what we expect.
	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got %v want %v",
			status, http.StatusOK)
	}

	// Check the response body is what we expect.
	expected := "<ListQueuesResult></ListQueuesResult>"
	if !strings.Contains(rr.Body.String(), expected) {
		t.Errorf("handler returned unexpected body: got %v want %v",
			rr.Body.String(), expected)
	}
}

func TestListQueues_POST_Success(t *testing.T) {
	req, err := http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	rr := httptest.NewRecorder()
	handler := http.HandlerFunc(ListQueues)

	app.SyncQueues.Queues["foo"] = &app.Queue{Name: "foo", URL: "http://:/queue/foo"}
	app.SyncQueues.Queues["bar"] = &app.Queue{Name: "bar", URL: "http://:/queue/bar"}
	app.SyncQueues.Queues["foobar"] = &app.Queue{Name: "foobar", URL: "http://:/queue/foobar"}

	handler.ServeHTTP(rr, req)

	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got %v want %v",
			status, http.StatusOK)
	}

	// Check the response body is what we expect.
	expected := "<QueueUrl>http://:/queue/bar</QueueUrl>"
	if !strings.Contains(rr.Body.String(), expected) {
		t.Errorf("handler returned unexpected body: got %v want %v",
			rr.Body.String(), expected)
	}

	// Filter lists by the given QueueNamePrefix
	form := url.Values{}
	form.Add("QueueNamePrefix", "fo")
	req, _ = http.NewRequest("POST", "/", nil)
	req.PostForm = form
	rr = httptest.NewRecorder()
	handler.ServeHTTP(rr, req)

	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got %v want %v",
			status, http.StatusOK)
	}

	// Check the response body is what we expect.
	unexpected := "<QueueUrl>http://:/queue/bar</QueueUrl>"
	if strings.Contains(rr.Body.String(), unexpected) {
		t.Errorf("handler returned unexpected body: got %v",
			rr.Body.String())
	}

}

func TestCreateQueuehandler_POST_CreateQueue(t *testing.T) {
	// Create a request to pass to our handler. We don't have any query parameters for now, so we'll
	// pass 'nil' as the third parameter.
	req, err := http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	queueName := "UnitTestQueue1"
	form := url.Values{}
	form.Add("Action", "CreateQueue")
	form.Add("QueueName", "UnitTestQueue1")
	form.Add("Attribute.1.Name", "VisibilityTimeout")
	form.Add("Attribute.1.Value", "60")
	form.Add("Attribute.2.Name", "MaximumMessageSize")
	form.Add("Attribute.2.Value", "2048")
	req.PostForm = form

	// We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response.
	rr := httptest.NewRecorder()
	handler := http.HandlerFunc(CreateQueue)

	// Our handlers satisfy http.Handler, so we can call their ServeHTTP method
	// directly and pass in our Request and ResponseRecorder.
	handler.ServeHTTP(rr, req)

	// Check the status code is what we expect.
	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got %v want %v",
			status, http.StatusOK)
	}

	// Check the response body is what we expect.
	expected := queueName
	if !strings.Contains(rr.Body.String(), expected) {
		t.Errorf("handler returned unexpected body: got %v want %v",
			rr.Body.String(), expected)
	}
	expectedQueue := &app.Queue{
		Name:        queueName,
		URL:         "http://://" + queueName,
		Arn:         "arn:aws:sqs:::" + queueName,
		TimeoutSecs: 60,
		MaximumMessageSize: 2048,
		Duplicates:  make(map[string]time.Time),
	}
	actualQueue := app.SyncQueues.Queues[queueName]
	if !reflect.DeepEqual(expectedQueue, actualQueue) {
		t.Fatalf("expected %+v, got %+v", expectedQueue, actualQueue)
	}
}

func TestCreateFIFOQueuehandler_POST_CreateQueue(t *testing.T) {
	req, err := http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	queueName := "UnitTestQueue1.fifo"
	form := url.Values{}
	form.Add("Action", "CreateQueue")
	form.Add("QueueName", "UnitTestQueue1.fifo")
	form.Add("Attribute.1.Name", "VisibilityTimeout")
	form.Add("Attribute.1.Value", "60")
	req.PostForm = form

	// We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response.
	rr := httptest.NewRecorder()
	handler := http.HandlerFunc(CreateQueue)

	// Our handlers satisfy http.Handler, so we can call their ServeHTTP method
	// directly and pass in our Request and ResponseRecorder.
	handler.ServeHTTP(rr, req)

	// Check the status code is what we expect.
	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got %v want %v",
			status, http.StatusOK)
	}

	// Check the response body is what we expect.
	expected := queueName
	if !strings.Contains(rr.Body.String(), expected) {
		t.Errorf("handler returned unexpected body: got %v want %v",
			rr.Body.String(), expected)
	}
	expectedQueue := &app.Queue{
		Name:        queueName,
		URL:         "http://://" + queueName,
		Arn:         "arn:aws:sqs:::" + queueName,
		TimeoutSecs: 60,
		IsFIFO:      true,
		Duplicates:   make(map[string]time.Time),
	}
	actualQueue := app.SyncQueues.Queues[queueName]
	if !reflect.DeepEqual(expectedQueue, actualQueue) {
		t.Fatalf("expected %+v, got %+v", expectedQueue, actualQueue)
	}
}

func TestSendMessage_MaximumMessageSize_Success(t *testing.T) {
	req, err := http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	app.SyncQueues.Queues["test_max_message_size"] =
		&app.Queue{Name: "test_max_message_size", MaximumMessageSize: 100}

	form := url.Values{}
	form.Add("Action", "SendMessage")
	form.Add("QueueUrl", "http://localhost:4100/queue/test_max_message_size")
	form.Add("MessageBody", "test%20message%20body%201")
	form.Add("Version", "2012-11-05")
	req.PostForm = form

	// We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response.
	rr := httptest.NewRecorder()
	handler := http.HandlerFunc(SendMessage)

	// Our handlers satisfy http.Handler, so we can call their ServeHTTP method
	// directly and pass in our Request and ResponseRecorder.
	handler.ServeHTTP(rr, req)

	// Check the status code is what we expect.
	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got %v want %v",
			status, http.StatusOK)
	}

	// Check the response body is what we expect.
	expected := "MD5OfMessageBody"
	if !strings.Contains(rr.Body.String(), expected) {
		t.Errorf("handler returned unexpected body: got %v want %v",
			rr.Body.String(), expected)
	}
}

func TestSendMessage_MaximumMessageSize_MessageTooBig(t *testing.T) {
	req, err := http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	app.SyncQueues.Queues["test_max_message_size"] =
		&app.Queue{Name: "test_max_message_size", MaximumMessageSize: 10}

	form := url.Values{}
	form.Add("Action", "SendMessage")
	form.Add("QueueUrl", "http://localhost:4100/queue/test_max_message_size")
	form.Add("MessageBody", "test%20message%20body%201")
	form.Add("Version", "2012-11-05")
	req.PostForm = form

	// We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response.
	rr := httptest.NewRecorder()
	handler := http.HandlerFunc(SendMessage)

	// Our handlers satisfy http.Handler, so we can call their ServeHTTP method
	// directly and pass in our Request and ResponseRecorder.
	handler.ServeHTTP(rr, req)

	// Check the status code is what we expect.
	if status := rr.Code; status != http.StatusBadRequest {
		t.Errorf("handler returned wrong status code: got %v want %v",
			status, http.StatusBadRequest)
	}

	// Check the response body is what we expect.
	expected := "MessageTooBig"
	if !strings.Contains(rr.Body.String(), expected) {
		t.Errorf("handler returned unexpected body: got %v want %v",
			rr.Body.String(), expected)
	}
}

func TestSendQueue_POST_NonExistant(t *testing.T) {
	// Create a request to pass to our handler. We don't have any query parameters for now, so we'll
	// pass 'nil' as the third parameter.
	req, err := http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	form := url.Values{}
	form.Add("Action", "SendMessage")
	form.Add("QueueUrl", "http://localhost:4100/queue/NON-EXISTANT")
	form.Add("MessageBody", "Test123")
	form.Add("Version", "2012-11-05")
	req.PostForm = form

	// We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response.
	rr := httptest.NewRecorder()
	handler := http.HandlerFunc(SendMessage)

	// Our handlers satisfy http.Handler, so we can call their ServeHTTP method
	// directly and pass in our Request and ResponseRecorder.
	handler.ServeHTTP(rr, req)

	// Check the status code is what we expect.
	if status := rr.Code; status != http.StatusBadRequest {
		t.Errorf("handler returned wrong status code: got %v want %v",
			status, http.StatusBadRequest)
	}

	// Check the response body is what we expect.
	expected := "NonExistentQueue"
	if !strings.Contains(rr.Body.String(), expected) {
		t.Errorf("handler returned unexpected body: got %v want %v",
			rr.Body.String(), expected)
	}
}

func TestSendMessageBatch_POST_QueueNotFound(t *testing.T) {
	req, err := http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	form := url.Values{}
	form.Add("Action", "SendMessageBatch")
	form.Add("QueueUrl", "http://localhost:4100/queue/testing")
	form.Add("SendMessageBatchRequestEntry.1.Id", "test_msg_001")
	form.Add("SendMessageBatchRequestEntry.1.MessageBody", "test%20message%20body%201")
	form.Add("SendMessageBatchRequestEntry.2.Id", "test_msg_002")
	form.Add("SendMessageBatchRequestEntry.2.MessageBody", "test%20message%20body%202")
	form.Add("Version", "2012-11-05")
	req.PostForm = form

	// We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response.
	rr := httptest.NewRecorder()
	handler := http.HandlerFunc(SendMessageBatch)

	// Our handlers satisfy http.Handler, so we can call their ServeHTTP method
	// directly and pass in our Request and ResponseRecorder.
	handler.ServeHTTP(rr, req)

	// Check the status code is what we expect.
	if status := rr.Code; status != http.StatusBadRequest {
		t.Errorf("handler returned wrong status code: got %v want %v",
			status, http.StatusBadRequest)
	}

	// Check the response body is what we expect.
	expected := "NonExistentQueue"
	if !strings.Contains(rr.Body.String(), expected) {
		t.Errorf("handler returned unexpected body: got %v want %v",
			rr.Body.String(), expected)
	}
}

func TestSendMessageBatch_POST_NoEntry(t *testing.T) {
	req, err := http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	app.SyncQueues.Queues["testing"] = &app.Queue{Name: "testing"}

	form := url.Values{}
	form.Add("Action", "SendMessageBatch")
	form.Add("QueueUrl", "http://localhost:4100/queue/testing")
	form.Add("Version", "2012-11-05")
	req.PostForm = form

	// We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response.
	rr := httptest.NewRecorder()
	handler := http.HandlerFunc(SendMessageBatch)

	// Our handlers satisfy http.Handler, so we can call their ServeHTTP method
	// directly and pass in our Request and ResponseRecorder.
	handler.ServeHTTP(rr, req)

	// Check the status code is what we expect.
	if status := rr.Code; status != http.StatusBadRequest {
		t.Errorf("handler returned wrong status code: got %v want %v",
			status, http.StatusBadRequest)
	}

	// Check the response body is what we expect.
	expected := "EmptyBatchRequest"
	if !strings.Contains(rr.Body.String(), expected) {
		t.Errorf("handler returned unexpected body: got %v want %v",
			rr.Body.String(), expected)
	}

	req, _ = http.NewRequest("POST", "/", nil)
	form.Add("SendMessageBatchRequestEntry", "")
	req.PostForm = form

	rr = httptest.NewRecorder()

	handler.ServeHTTP(rr, req)

	if status := rr.Code; status != http.StatusBadRequest {
		t.Errorf("handler returned wrong status code: got %v want %v",
			status, http.StatusBadRequest)
	}

	if !strings.Contains(rr.Body.String(), expected) {
		t.Errorf("handler returned unexpected body: got %v want %v",
			rr.Body.String(), expected)
	}
}

func TestSendMessageBatch_POST_IdNotDistinct(t *testing.T) {
	req, err := http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	app.SyncQueues.Queues["testing"] = &app.Queue{Name: "testing"}

	form := url.Values{}
	form.Add("Action", "SendMessageBatch")
	form.Add("QueueUrl", "http://localhost:4100/queue/testing")
	form.Add("SendMessageBatchRequestEntry.1.Id", "test_msg_001")
	form.Add("SendMessageBatchRequestEntry.1.MessageBody", "test%20message%20body%201")
	form.Add("SendMessageBatchRequestEntry.2.Id", "test_msg_001")
	form.Add("SendMessageBatchRequestEntry.2.MessageBody", "test%20message%20body%202")
	form.Add("Version", "2012-11-05")
	req.PostForm = form

	// We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response.
	rr := httptest.NewRecorder()
	handler := http.HandlerFunc(SendMessageBatch)

	// Our handlers satisfy http.Handler, so we can call their ServeHTTP method
	// directly and pass in our Request and ResponseRecorder.
	handler.ServeHTTP(rr, req)

	// Check the status code is what we expect.
	if status := rr.Code; status != http.StatusBadRequest {
		t.Errorf("handler returned wrong status code: got %v want %v",
			status, http.StatusBadRequest)
	}

	// Check the response body is what we expect.
	expected := "BatchEntryIdsNotDistinct"
	if !strings.Contains(rr.Body.String(), expected) {
		t.Errorf("handler returned unexpected body: got %v want %v",
			rr.Body.String(), expected)
	}
}

func TestSendMessageBatch_POST_TooManyEntries(t *testing.T) {
	req, err := http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	app.SyncQueues.Queues["testing"] = &app.Queue{Name: "testing"}

	form := url.Values{}
	form.Add("Action", "SendMessageBatch")
	form.Add("QueueUrl", "http://localhost:4100/queue/testing")
	form.Add("SendMessageBatchRequestEntry.1.Id", "test_msg_001")
	form.Add("SendMessageBatchRequestEntry.1.MessageBody", "test%20message%20body%201")
	form.Add("SendMessageBatchRequestEntry.2.Id", "test_msg_002")
	form.Add("SendMessageBatchRequestEntry.2.MessageBody", "test%20message%20body%202")
	form.Add("SendMessageBatchRequestEntry.3.Id", "test_msg_003")
	form.Add("SendMessageBatchRequestEntry.3.MessageBody", "test%20message%20body%202")
	form.Add("SendMessageBatchRequestEntry.4.Id", "test_msg_004")
	form.Add("SendMessageBatchRequestEntry.4.MessageBody", "test%20message%20body%202")
	form.Add("SendMessageBatchRequestEntry.5.Id", "test_msg_005")
	form.Add("SendMessageBatchRequestEntry.5.MessageBody", "test%20message%20body%202")
	form.Add("SendMessageBatchRequestEntry.6.Id", "test_msg_006")
	form.Add("SendMessageBatchRequestEntry.6.MessageBody", "test%20message%20body%202")
	form.Add("SendMessageBatchRequestEntry.7.Id", "test_msg_007")
	form.Add("SendMessageBatchRequestEntry.7.MessageBody", "test%20message%20body%202")
	form.Add("SendMessageBatchRequestEntry.8.Id", "test_msg_008")
	form.Add("SendMessageBatchRequestEntry.8.MessageBody", "test%20message%20body%202")
	form.Add("SendMessageBatchRequestEntry.9.Id", "test_msg_009")
	form.Add("SendMessageBatchRequestEntry.9.MessageBody", "test%20message%20body%202")
	form.Add("SendMessageBatchRequestEntry.10.Id", "test_msg_010")
	form.Add("SendMessageBatchRequestEntry.10.MessageBody", "test%20message%20body%202")
	form.Add("SendMessageBatchRequestEntry.11.Id", "test_msg_011")
	form.Add("SendMessageBatchRequestEntry.11.MessageBody", "test%20message%20body%202")
	form.Add("Version", "2012-11-05")
	req.PostForm = form

	// We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response.
	rr := httptest.NewRecorder()
	handler := http.HandlerFunc(SendMessageBatch)

	// Our handlers satisfy http.Handler, so we can call their ServeHTTP method
	// directly and pass in our Request and ResponseRecorder.
	handler.ServeHTTP(rr, req)

	// Check the status code is what we expect.
	if status := rr.Code; status != http.StatusBadRequest {
		t.Errorf("handler returned wrong status code: got %v want %v",
			status, http.StatusBadRequest)
	}

	// Check the response body is what we expect.
	expected := "TooManyEntriesInBatchRequest"
	if !strings.Contains(rr.Body.String(), expected) {
		t.Errorf("handler returned unexpected body: got %v want %v",
			rr.Body.String(), expected)
	}
}

func TestSendMessageBatch_POST_Success(t *testing.T) {
	req, err := http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	app.SyncQueues.Queues["testing"] = &app.Queue{Name: "testing"}

	form := url.Values{}
	form.Add("Action", "SendMessageBatch")
	form.Add("QueueUrl", "http://localhost:4100/queue/testing")
	form.Add("SendMessageBatchRequestEntry.1.Id", "test_msg_001")
	form.Add("SendMessageBatchRequestEntry.1.MessageBody", "test%20message%20body%201")
	form.Add("SendMessageBatchRequestEntry.2.Id", "test_msg_002")
	form.Add("SendMessageBatchRequestEntry.2.MessageBody", "test%20message%20body%202")
	form.Add("SendMessageBatchRequestEntry.2.MessageAttribute.1.Name", "test_attribute_name_1")
	form.Add("SendMessageBatchRequestEntry.2.MessageAttribute.1.Value.StringValue", "test_attribute_value_1")
	form.Add("SendMessageBatchRequestEntry.2.MessageAttribute.1.Value.DataType", "String")
	form.Add("Version", "2012-11-05")
	req.PostForm = form

	// We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response.
	rr := httptest.NewRecorder()
	handler := http.HandlerFunc(SendMessageBatch)

	// Our handlers satisfy http.Handler, so we can call their ServeHTTP method
	// directly and pass in our Request and ResponseRecorder.
	handler.ServeHTTP(rr, req)

	// Check the status code is what we expect.
	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got \n%v want %v",
			status, http.StatusOK)
	}

	// Check the response body is what we expect.
	expected := "<MD5OfMessageBody>1c538b76fce1a234bce865025c02b042</MD5OfMessageBody>"
	if !strings.Contains(rr.Body.String(), expected) {
		t.Errorf("handler returned unexpected body: got %v want %v",
			rr.Body.String(), expected)
	}
}

func TestSendMessageBatchToFIFOQueue_POST_Success(t *testing.T) {
	req, err := http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	app.SyncQueues.Queues["testing.fifo"] = &app.Queue{
		Name:   "testing.fifo",
		IsFIFO: true,
	}

	form := url.Values{}
	form.Add("Action", "SendMessageBatch")
	form.Add("QueueUrl", "http://localhost:4100/queue/testing.fifo")
	form.Add("SendMessageBatchRequestEntry.1.Id", "test_msg_001")
	form.Add("SendMessageBatchRequestEntry.1.MessageGroupId", "GROUP-X")
	form.Add("SendMessageBatchRequestEntry.1.MessageBody", "test%20message%20body%201")
	form.Add("SendMessageBatchRequestEntry.2.Id", "test_msg_002")
	form.Add("SendMessageBatchRequestEntry.2.MessageGroupId", "GROUP-X")
	form.Add("SendMessageBatchRequestEntry.2.MessageBody", "test%20message%20body%202")
	form.Add("SendMessageBatchRequestEntry.2.MessageAttribute.1.Name", "test_attribute_name_1")
	form.Add("SendMessageBatchRequestEntry.2.MessageAttribute.1.Value.StringValue", "test_attribute_value_1")
	form.Add("SendMessageBatchRequestEntry.2.MessageAttribute.1.Value.DataType", "String")
	form.Add("Version", "2012-11-05")
	req.PostForm = form

	// We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response.
	rr := httptest.NewRecorder()
	handler := http.HandlerFunc(SendMessageBatch)

	// Our handlers satisfy http.Handler, so we can call their ServeHTTP method
	// directly and pass in our Request and ResponseRecorder.
	handler.ServeHTTP(rr, req)

	// Check the status code is what we expect.
	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got \n%v want %v",
			status, http.StatusOK)
	}

	// Check the response body is what we expect.
	expected := "<MD5OfMessageBody>1c538b76fce1a234bce865025c02b042</MD5OfMessageBody>"
	if !strings.Contains(rr.Body.String(), expected) {
		t.Errorf("handler returned unexpected body: got %v want %v",
			rr.Body.String(), expected)
	}
}

func TestChangeMessageVisibility_POST_SUCCESS(t *testing.T) {
	req, err := http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	app.SyncQueues.Queues["testing"] = &app.Queue{Name: "testing"}
	app.SyncQueues.Queues["testing"].Messages = []app.Message{{
		MessageBody:   []byte("test1"),
		ReceiptHandle: "123",
	}}

	form := url.Values{}
	form.Add("Action", "ChangeMessageVisibility")
	form.Add("QueueUrl", "http://localhost:4100/queue/testing")
	form.Add("VisibilityTimeout", "0")
	form.Add("ReceiptHandle", "123")
	form.Add("Version", "2012-11-05")
	req.PostForm = form

	// We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response.
	rr := httptest.NewRecorder()
	handler := http.HandlerFunc(ChangeMessageVisibility)

	// Our handlers satisfy http.Handler, so we can call their ServeHTTP method
	// directly and pass in our Request and ResponseRecorder.
	handler.ServeHTTP(rr, req)

	// Check the status code is what we expect.
	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got \n%v want %v",
			status, http.StatusOK)
	}

	// Check the response body is what we expect.
	expected := `<ChangeMessageVisibilityResult xmlns="http://queue.amazonaws.com/doc/2012-11-05/">`
	if !strings.Contains(rr.Body.String(), expected) {
		t.Errorf("handler returned unexpected body: got %v want %v",
			rr.Body.String(), expected)
	}
}

func TestRequeueing_VisibilityTimeoutExpires(t *testing.T) {
	done := make(chan struct{}, 0)
	go PeriodicTasks(1*time.Second, done)

	// create a queue
	req, err := http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	form := url.Values{}
	form.Add("Action", "CreateQueue")
	form.Add("QueueName", "requeue")
	form.Add("Attribute.1.Name", "VisibilityTimeout")
	form.Add("Attribute.1.Value", "1")
	form.Add("Version", "2012-11-05")
	req.PostForm = form

	rr := httptest.NewRecorder()
	http.HandlerFunc(CreateQueue).ServeHTTP(rr, req)

	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got \n%v want %v",
			status, http.StatusOK)
	}

	// send a message
	req, err = http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	form = url.Values{}
	form.Add("Action", "SendMessage")
	form.Add("QueueUrl", "http://localhost:4100/queue/requeue")
	form.Add("MessageBody", "1")
	form.Add("Version", "2012-11-05")
	req.PostForm = form

	rr = httptest.NewRecorder()
	http.HandlerFunc(SendMessage).ServeHTTP(rr, req)

	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got \n%v want %v",
			status, http.StatusOK)
	}

	// receive message
	req, err = http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	form = url.Values{}
	form.Add("Action", "ReceiveMessage")
	form.Add("QueueUrl", "http://localhost:4100/queue/requeue")
	form.Add("Version", "2012-11-05")
	req.PostForm = form

	rr = httptest.NewRecorder()
	http.HandlerFunc(ReceiveMessage).ServeHTTP(rr, req)

	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got \n%v want %v",
			status, http.StatusOK)
	}
	if ok := strings.Contains(rr.Body.String(), "<Message>"); !ok {
		t.Fatal("handler should return a message")
	}

	// try to receive another message.
	req, err = http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	form = url.Values{}
	form.Add("Action", "ReceiveMessage")
	form.Add("QueueUrl", "http://localhost:4100/queue/requeue")
	form.Add("Version", "2012-11-05")
	req.PostForm = form

	rr = httptest.NewRecorder()
	http.HandlerFunc(ReceiveMessage).ServeHTTP(rr, req)

	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got \n%v want %v",
			status, http.StatusOK)
	}
	if ok := strings.Contains(rr.Body.String(), "<Message>"); ok {
		t.Fatal("handler should not return a message")
	}
	time.Sleep(2 * time.Second)

	// message needs to be requeued
	req, err = http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	form = url.Values{}
	form.Add("Action", "ReceiveMessage")
	form.Add("QueueUrl", "http://localhost:4100/queue/requeue")
	form.Add("Version", "2012-11-05")
	req.PostForm = form

	rr = httptest.NewRecorder()
	http.HandlerFunc(ReceiveMessage).ServeHTTP(rr, req)

	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got \n%v want %v",
			status, http.StatusOK)
	}
	if ok := strings.Contains(rr.Body.String(), "<Message>"); !ok {
		t.Fatal("handler should return a message")
	}
	done <- struct{}{}
}

func TestRequeueing_ResetVisibilityTimeout(t *testing.T) {
	done := make(chan struct{}, 0)
	go PeriodicTasks(1*time.Second, done)

	// create a queue
	req, err := http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	form := url.Values{}
	form.Add("Action", "CreateQueue")
	form.Add("QueueName", "requeue-reset")
	form.Add("Attribute.1.Name", "VisibilityTimeout")
	form.Add("Attribute.1.Value", "10")
	form.Add("Version", "2012-11-05")
	req.PostForm = form

	rr := httptest.NewRecorder()
	http.HandlerFunc(CreateQueue).ServeHTTP(rr, req)

	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got \n%v want %v",
			status, http.StatusOK)
	}

	// send a message
	req, err = http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	form = url.Values{}
	form.Add("Action", "SendMessage")
	form.Add("QueueUrl", "http://localhost:4100/queue/requeue-reset")
	form.Add("MessageBody", "1")
	form.Add("Version", "2012-11-05")
	req.PostForm = form

	rr = httptest.NewRecorder()
	http.HandlerFunc(SendMessage).ServeHTTP(rr, req)

	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got \n%v want %v",
			status, http.StatusOK)
	}

	// receive message
	req, err = http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	form = url.Values{}
	form.Add("Action", "ReceiveMessage")
	form.Add("QueueUrl", "http://localhost:4100/queue/requeue-reset")
	form.Add("Version", "2012-11-05")
	req.PostForm = form

	rr = httptest.NewRecorder()
	http.HandlerFunc(ReceiveMessage).ServeHTTP(rr, req)

	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got \n%v want %v",
			status, http.StatusOK)
	}
	if ok := strings.Contains(rr.Body.String(), "<Message>"); !ok {
		t.Fatal("handler should return a message")
	}

	resp := app.ReceiveMessageResponse{}
	err = xml.Unmarshal(rr.Body.Bytes(), &resp)
	if err != nil {
		t.Fatalf("unexpected unmarshal error: %s", err)
	}
	receiptHandle := resp.Result.Message[0].ReceiptHandle

	// try to receive another message.
	req, err = http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	form = url.Values{}
	form.Add("Action", "ReceiveMessage")
	form.Add("QueueUrl", "http://localhost:4100/queue/requeue-reset")
	form.Add("Version", "2012-11-05")
	req.PostForm = form

	rr = httptest.NewRecorder()
	http.HandlerFunc(ReceiveMessage).ServeHTTP(rr, req)

	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got \n%v want %v",
			status, http.StatusOK)
	}
	if ok := strings.Contains(rr.Body.String(), "<Message>"); ok {
		t.Fatal("handler should not return a message")
	}

	// reset message visibility timeout to requeue it
	req, err = http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	form = url.Values{}
	form.Add("Action", "ChangeMessageVisibility")
	form.Add("QueueUrl", "http://localhost:4100/queue/requeue-reset")
	form.Add("VisibilityTimeout", "0")
	form.Add("ReceiptHandle", receiptHandle)
	form.Add("Version", "2012-11-05")
	req.PostForm = form

	rr = httptest.NewRecorder()
	http.HandlerFunc(ChangeMessageVisibility).ServeHTTP(rr, req)

	// Check the status code is what we expect.
	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got \n%v want %v",
			status, http.StatusOK)
	}

	// message needs to be requeued
	req, err = http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	form = url.Values{}
	form.Add("Action", "ReceiveMessage")
	form.Add("QueueUrl", "http://localhost:4100/queue/requeue-reset")
	form.Add("Version", "2012-11-05")
	req.PostForm = form

	rr = httptest.NewRecorder()
	http.HandlerFunc(ReceiveMessage).ServeHTTP(rr, req)

	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got \n%v want %v",
			status, http.StatusOK)
	}
	if ok := strings.Contains(rr.Body.String(), "<Message>"); !ok {
		t.Fatal("handler should return a message")
	}
	done <- struct{}{}
}

func TestDeadLetterQueue(t *testing.T) {
	done := make(chan struct{}, 0)
	go PeriodicTasks(1*time.Second, done)

	// create a queue
	req, err := http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}
	deadLetterQueue := &app.Queue{
		Name:     "failed-messages",
		Messages: []app.Message{},
	}
	app.SyncQueues.Lock()
	app.SyncQueues.Queues["failed-messages"] = deadLetterQueue
	app.SyncQueues.Unlock()
	form := url.Values{}
	form.Add("Action", "CreateQueue")
	form.Add("QueueName", "testing-deadletter")
	form.Add("Attribute.1.Name", "VisibilityTimeout")
	form.Add("Attribute.1.Value", "1")
	form.Add("Attribute.2.Name", "RedrivePolicy")
	form.Add("Attribute.2.Value", `{"maxReceiveCount": 1, "deadLetterTargetArn":"arn:aws:sqs::000000000000:failed-messages"}`)
	form.Add("Version", "2012-11-05")
	req.PostForm = form

	rr := httptest.NewRecorder()
	http.HandlerFunc(CreateQueue).ServeHTTP(rr, req)

	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got \n%v want %v",
			status, http.StatusOK)
	}

	// send a message
	req, err = http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	form = url.Values{}
	form.Add("Action", "SendMessage")
	form.Add("QueueUrl", "http://localhost:4100/queue/testing-deadletter")
	form.Add("MessageBody", "1")
	form.Add("Version", "2012-11-05")
	req.PostForm = form

	rr = httptest.NewRecorder()
	http.HandlerFunc(SendMessage).ServeHTTP(rr, req)

	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got \n%v want %v",
			status, http.StatusOK)
	}

	// receive message
	req, err = http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	form = url.Values{}
	form.Add("Action", "ReceiveMessage")
	form.Add("QueueUrl", "http://localhost:4100/queue/testing-deadletter")
	form.Add("Version", "2012-11-05")
	req.PostForm = form

	rr = httptest.NewRecorder()
	http.HandlerFunc(ReceiveMessage).ServeHTTP(rr, req)

	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got \n%v want %v",
			status, http.StatusOK)
	}
	if ok := strings.Contains(rr.Body.String(), "<Message>"); !ok {
		t.Fatal("handler should return a message")
	}

	time.Sleep(2 * time.Second)

	// receive the message one more time
	req, err = http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	req.PostForm = form

	rr = httptest.NewRecorder()
	http.HandlerFunc(ReceiveMessage).ServeHTTP(rr, req)

	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got \n%v want %v",
			status, http.StatusOK)
	}
	if ok := strings.Contains(rr.Body.String(), "<Message>"); !ok {
		t.Fatal("handler should return a message")
	}
	time.Sleep(2 * time.Second)

	// another receive attempt
	req, err = http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	req.PostForm = form

	rr = httptest.NewRecorder()
	http.HandlerFunc(ReceiveMessage).ServeHTTP(rr, req)

	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got \n%v want %v",
			status, http.StatusOK)
	}
	if ok := strings.Contains(rr.Body.String(), "<Message>"); ok {
		t.Fatal("handler should not return a message")
	}
	if len(deadLetterQueue.Messages) == 0 {
		t.Fatal("expected a message")
	}

}

func TestReceiveMessageWaitTimeEnforced(t *testing.T) {
	// create a queue
	req, err := http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}
	form := url.Values{}
	form.Add("Action", "CreateQueue")
	form.Add("QueueName", "waiting-queue")
	form.Add("Attribute.1.Name", "ReceiveMessageWaitTimeSeconds")
	form.Add("Attribute.1.Value", "2")
	form.Add("Version", "2012-11-05")
	req.PostForm = form

	rr := httptest.NewRecorder()
	http.HandlerFunc(CreateQueue).ServeHTTP(rr, req)

	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got \n%v want %v",
			status, http.StatusOK)
	}

	// receive message ensure delay
	req, err = http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	form = url.Values{}
	form.Add("Action", "ReceiveMessage")
	form.Add("QueueUrl", "http://localhost:4100/queue/waiting-queue")
	form.Add("Version", "2012-11-05")
	req.PostForm = form

	rr = httptest.NewRecorder()

	start := time.Now()
	http.HandlerFunc(ReceiveMessage).ServeHTTP(rr, req)
	elapsed := time.Since(start)

	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got \n%v want %v",
			status, http.StatusOK)
	}
	if ok := strings.Contains(rr.Body.String(), "<Message>"); ok {
		t.Fatal("handler should not return a message")
	}
	if elapsed < 2*time.Second {
		t.Fatal("handler didn't wait ReceiveMessageWaitTimeSeconds")
	}

	// send a message
	req, err = http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	form = url.Values{}
	form.Add("Action", "SendMessage")
	form.Add("QueueUrl", "http://localhost:4100/queue/waiting-queue")
	form.Add("MessageBody", "1")
	form.Add("Version", "2012-11-05")
	req.PostForm = form

	rr = httptest.NewRecorder()
	http.HandlerFunc(SendMessage).ServeHTTP(rr, req)

	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got \n%v want %v",
			status, http.StatusOK)
	}

	// receive message
	req, err = http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	form = url.Values{}
	form.Add("Action", "ReceiveMessage")
	form.Add("QueueUrl", "http://localhost:4100/queue/waiting-queue")
	form.Add("Version", "2012-11-05")
	req.PostForm = form

	rr = httptest.NewRecorder()

	start = time.Now()
	http.HandlerFunc(ReceiveMessage).ServeHTTP(rr, req)
	elapsed = time.Since(start)

	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got \n%v want %v",
			status, http.StatusOK)
	}
	if ok := strings.Contains(rr.Body.String(), "<Message>"); !ok {
		t.Fatal("handler should return a message")
	}
	if elapsed > 1*time.Second {
		t.Fatal("handler waited when message was available, expected not to wait")
	}
}
func TestReceiveMessage_CanceledByClient(t *testing.T) {
	// create a queue
	req, err := http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}
	form := url.Values{}
	form.Add("Action", "CreateQueue")
	form.Add("QueueName", "cancel-queue")
	form.Add("Attribute.1.Name", "ReceiveMessageWaitTimeSeconds")
	form.Add("Attribute.1.Value", "20")
	form.Add("Version", "2012-11-05")
	req.PostForm = form

	rr := httptest.NewRecorder()
	http.HandlerFunc(CreateQueue).ServeHTTP(rr, req)

	var wg sync.WaitGroup
	ctx, cancelReceive := context.WithCancel(context.Background())

	wg.Add(1)
	go func() {
		defer wg.Done()
		// receive message (that will be canceled)
		req, err := http.NewRequest("POST", "/", nil)
		req = req.WithContext(ctx)
		if err != nil {
			t.Fatal(err)
		}

		form := url.Values{}
		form.Add("Action", "ReceiveMessage")
		form.Add("QueueUrl", "http://localhost:4100/queue/cancel-queue")
		form.Add("Version", "2012-11-05")
		req.PostForm = form

		rr := httptest.NewRecorder()
		http.HandlerFunc(ReceiveMessage).ServeHTTP(rr, req)

		if status := rr.Code; status != http.StatusOK {
			t.Errorf("handler returned wrong status code: got \n%v want %v",
				status, http.StatusOK)
		}

		if ok := strings.Contains(rr.Body.String(), "12345"); ok {
			t.Fatal("expecting this ReceiveMessage() to not pickup this message as it should canceled before the Send()")
		}
	}()
	time.Sleep(100 * time.Millisecond) // let enought time for the Receive go to wait mode
	cancelReceive()                    // cancel the first ReceiveMessage(), make sure it will not pickup the sent message below
	time.Sleep(5 * time.Millisecond)

	// send a message
	req, err = http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	form = url.Values{}
	form.Add("Action", "SendMessage")
	form.Add("QueueUrl", "http://localhost:4100/queue/cancel-queue")
	form.Add("MessageBody", "12345")
	form.Add("Version", "2012-11-05")
	req.PostForm = form

	rr = httptest.NewRecorder()
	http.HandlerFunc(SendMessage).ServeHTTP(rr, req)

	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got \n%v want %v",
			status, http.StatusOK)
	}

	// receive message
	req, err = http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	form = url.Values{}
	form.Add("Action", "ReceiveMessage")
	form.Add("QueueUrl", "http://localhost:4100/queue/cancel-queue")
	form.Add("Version", "2012-11-05")
	req.PostForm = form

	rr = httptest.NewRecorder()

	start := time.Now()
	http.HandlerFunc(ReceiveMessage).ServeHTTP(rr, req)
	elapsed := time.Since(start)

	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got \n%v want %v",
			status, http.StatusOK)
	}
	if ok := strings.Contains(rr.Body.String(), "12345"); !ok {
		t.Fatal("handler should return a message")
	}
	if elapsed > 1*time.Second {
		t.Fatal("handler waited when message was available, expected not to wait")
	}

	if timedout := waitTimeout(&wg, 2*time.Second); timedout {
		t.Errorf("expected ReceiveMessage() in goroutine to exit quickly due to cancelReceive() called")
	}
}

func TestReceiveMessage_WithConcurrentDeleteQueue(t *testing.T) {
	// create a queue
	req, err := http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}
	form := url.Values{}
	form.Add("Action", "CreateQueue")
	form.Add("QueueName", "waiting-queue")
	form.Add("Attribute.1.Name", "ReceiveMessageWaitTimeSeconds")
	form.Add("Attribute.1.Value", "1")
	form.Add("Version", "2012-11-05")
	req.PostForm = form

	rr := httptest.NewRecorder()
	http.HandlerFunc(CreateQueue).ServeHTTP(rr, req)

	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got \n%v want %v",
			status, http.StatusOK)
	}

	var wg sync.WaitGroup

	wg.Add(1)
	go func() {
		defer wg.Done()
		// receive message
		req, err := http.NewRequest("POST", "/", nil)
		if err != nil {
			t.Fatal(err)
		}

		form := url.Values{}
		form.Add("Action", "ReceiveMessage")
		form.Add("QueueUrl", "http://localhost:4100/queue/waiting-queue")
		form.Add("Version", "2012-11-05")
		req.PostForm = form

		rr := httptest.NewRecorder()

		http.HandlerFunc(ReceiveMessage).ServeHTTP(rr, req)

		// Check the status code is what we expect.
		if status := rr.Code; status != http.StatusBadRequest {
			t.Errorf("handler returned wrong status code: got %v want %v",
				status, http.StatusBadRequest)
		}

		// Check the response body is what we expect.
		expected := "QueueNotFound"
		if !strings.Contains(rr.Body.String(), "Not Found") {
			t.Errorf("handler returned unexpected body: got %v want %v",
				rr.Body.String(), expected)
		}
	}()

	wg.Add(1)
	go func() {
		defer wg.Done()
		time.Sleep(10 * time.Millisecond) // 10ms to let the ReceiveMessage() block
		// delete queue message
		req, err := http.NewRequest("POST", "/", nil)
		if err != nil {
			t.Fatal(err)
		}
		form := url.Values{}
		form.Add("Action", "DeleteQueue")
		form.Add("QueueUrl", "http://localhost:4100/queue/waiting-queue")
		form.Add("Version", "2012-11-05")
		req.PostForm = form

		rr := httptest.NewRecorder()
		http.HandlerFunc(DeleteQueue).ServeHTTP(rr, req)

		if status := rr.Code; status != http.StatusOK {
			t.Errorf("handler returned wrong status code: got \n%v want %v",
				status, http.StatusOK)
		}
	}()

	if timedout := waitTimeout(&wg, 2*time.Second); timedout {
		t.Errorf("concurrent handlers timeout, expecting both to return within timeout")
	}

}

func TestSetQueueAttributes_POST_QueueNotFound(t *testing.T) {
	req, err := http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	form := url.Values{}
	form.Add("Action", "SetQueueAttributes")
	form.Add("QueueUrl", "http://localhost:4100/queue/not-existing")
	form.Add("Version", "2012-11-05")
	req.PostForm = form

	// We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response.
	rr := httptest.NewRecorder()
	handler := http.HandlerFunc(SetQueueAttributes)

	// Our handlers satisfy http.Handler, so we can call their ServeHTTP method
	// directly and pass in our Request and ResponseRecorder.
	handler.ServeHTTP(rr, req)

	// Check the status code is what we expect.
	if status := rr.Code; status != http.StatusBadRequest {
		t.Errorf("handler returned wrong status code: got %v want %v",
			status, http.StatusBadRequest)
	}

	// Check the response body is what we expect.
	expected := "NonExistentQueue"
	if !strings.Contains(rr.Body.String(), expected) {
		t.Errorf("handler returned unexpected body: got %v want %v",
			rr.Body.String(), expected)
	}
}

func TestSendingAndReceivingFromFIFOQueueReturnsSameMessageOnError(t *testing.T) {
	done := make(chan struct{}, 0)
	go PeriodicTasks(1*time.Second, done)

	// create a queue
	req, err := http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	form := url.Values{}
	form.Add("Action", "CreateQueue")
	form.Add("QueueName", "requeue-reset.fifo")
	form.Add("Attribute.1.Name", "VisibilityTimeout")
	form.Add("Attribute.1.Value", "2")
	form.Add("Version", "2012-11-05")
	req.PostForm = form

	rr := httptest.NewRecorder()
	http.HandlerFunc(CreateQueue).ServeHTTP(rr, req)

	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got \n%v want %v",
			status, http.StatusOK)
	}

	// send a message
	req, err = http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	form = url.Values{}
	form.Add("Action", "SendMessage")
	form.Add("QueueUrl", "http://localhost:4100/queue/requeue-reset.fifo")
	form.Add("MessageBody", "1")
	form.Add("MessageGroupId", "GROUP-X")
	form.Add("Version", "2012-11-05")
	req.PostForm = form

	rr = httptest.NewRecorder()
	http.HandlerFunc(SendMessage).ServeHTTP(rr, req)

	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got \n%v want %v",
			status, http.StatusOK)
	}

	// send a message
	req, err = http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	form = url.Values{}
	form.Add("Action", "SendMessage")
	form.Add("QueueUrl", "http://localhost:4100/queue/requeue-reset.fifo")
	form.Add("MessageBody", "2")
	form.Add("MessageGroupId", "GROUP-X")
	form.Add("Version", "2012-11-05")
	req.PostForm = form

	rr = httptest.NewRecorder()
	http.HandlerFunc(SendMessage).ServeHTTP(rr, req)

	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got \n%v want %v",
			status, http.StatusOK)
	}

	// receive message
	req, err = http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	form = url.Values{}
	form.Add("Action", "ReceiveMessage")
	form.Add("QueueUrl", "http://localhost:4100/queue/requeue-reset.fifo")
	form.Add("Version", "2012-11-05")
	req.PostForm = form

	rr = httptest.NewRecorder()
	http.HandlerFunc(ReceiveMessage).ServeHTTP(rr, req)

	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got \n%v want %v",
			status, http.StatusOK)
	}
	if ok := strings.Contains(rr.Body.String(), "<Message>"); !ok {
		t.Fatal("handler should return a message")
	}

	resp := app.ReceiveMessageResponse{}
	err = xml.Unmarshal(rr.Body.Bytes(), &resp)
	if err != nil {
		t.Fatalf("unexpected unmarshal error: %s", err)
	}
	receiptHandleFirst := resp.Result.Message[0].ReceiptHandle
	if string(resp.Result.Message[0].Body) != "1" {
		t.Fatalf("should have received body 1: %s", err)
	}

	// try to receive another message and we should get none
	req, err = http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	form = url.Values{}
	form.Add("Action", "ReceiveMessage")
	form.Add("QueueUrl", "http://localhost:4100/queue/requeue-reset.fifo")
	form.Add("Version", "2012-11-05")
	req.PostForm = form

	rr = httptest.NewRecorder()
	http.HandlerFunc(ReceiveMessage).ServeHTTP(rr, req)

	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got \n%v want %v",
			status, http.StatusOK)
	}
	if ok := strings.Contains(rr.Body.String(), "<Message>"); ok {
		t.Fatal("handler should not return a message")
	}

	if len(app.SyncQueues.Queues["requeue-reset.fifo"].FIFOMessages) != 1 {
		t.Fatal("there should be only 1 group locked")
	}

	if app.SyncQueues.Queues["requeue-reset.fifo"].FIFOMessages["GROUP-X"] != 0 {
		t.Fatal("there should be GROUP-X locked")
	}

	// remove message
	req, err = http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	form = url.Values{}
	form.Add("Action", "DeleteMessage")
	form.Add("QueueUrl", "http://localhost:4100/queue/requeue-reset.fifo")
	form.Add("ReceiptHandle", receiptHandleFirst)
	form.Add("Version", "2012-11-05")
	req.PostForm = form

	rr = httptest.NewRecorder()
	http.HandlerFunc(DeleteMessage).ServeHTTP(rr, req)

	// Check the status code is what we expect.
	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got \n%v want %v",
			status, http.StatusOK)
	}
	if len(app.SyncQueues.Queues["requeue-reset.fifo"].Messages) != 1 {
		t.Fatal("there should be only 1 message in queue")
	}

	// receive message - loop until visibility timeouts
	for {
		req, err = http.NewRequest("POST", "/", nil)
		if err != nil {
			t.Fatal(err)
		}

		form = url.Values{}
		form.Add("Action", "ReceiveMessage")
		form.Add("QueueUrl", "http://localhost:4100/queue/requeue-reset.fifo")
		form.Add("Version", "2012-11-05")
		req.PostForm = form

		rr = httptest.NewRecorder()
		http.HandlerFunc(ReceiveMessage).ServeHTTP(rr, req)

		if status := rr.Code; status != http.StatusOK {
			t.Errorf("handler returned wrong status code: got \n%v want %v",
				status, http.StatusOK)
		}
		if ok := strings.Contains(rr.Body.String(), "<Message>"); !ok {
			continue
		}

		resp = app.ReceiveMessageResponse{}
		err = xml.Unmarshal(rr.Body.Bytes(), &resp)
		if err != nil {
			t.Fatalf("unexpected unmarshal error: %s", err)
		}
		if string(resp.Result.Message[0].Body) != "2" {
			t.Fatalf("should have received body 2: %s", err)
		}
		break
	}

	done <- struct{}{}
}

func TestSendMessage_POST_DuplicatationNotAppliedToStandardQueue(t *testing.T) {
	done := make(chan struct{}, 0)
	go PeriodicTasks(1*time.Second, done)

	// create a queue
	req, err := http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	form := url.Values{}
	form.Add("Action", "CreateQueue")
	form.Add("QueueName", "stantdard-testing")
	form.Add("Version", "2012-11-05")
	req.PostForm = form

	rr := httptest.NewRecorder()
	http.HandlerFunc(CreateQueue).ServeHTTP(rr, req)

	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got \n%v want %v",
			status, http.StatusOK)
	}

	req, err = http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	form = url.Values{}
	form.Add("Action", "SendMessage")
	form.Add("QueueUrl", "http://localhost:4100/queue/stantdard-testing")
	form.Add("MessageBody", "Test1")
	form.Add("MessageDeduplicationId", "123")
	form.Add("Version", "2012-11-05")
	req.PostForm = form

	rr = httptest.NewRecorder()
	http.HandlerFunc(SendMessage).ServeHTTP(rr, req)

	// Check the status code is what we expect.
	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got \n%v want %v",
			status, http.StatusOK)
	}
	if len(app.SyncQueues.Queues["stantdard-testing"].Messages) == 0 {
		t.Fatal("there should be 1 message in queue")
	}

	form = url.Values{}
	form.Add("Action", "SendMessage")
	form.Add("QueueUrl", "http://localhost:4100/queue/stantdard-testing")
	form.Add("MessageBody", "Test2")
	form.Add("MessageDeduplicationId", "123")
	form.Add("Version", "2012-11-05")
	req.PostForm = form

	rr = httptest.NewRecorder()
	http.HandlerFunc(SendMessage).ServeHTTP(rr, req)

	// Check the status code is what we expect.
	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got \n%v want %v",
			status, http.StatusOK)
	}
	if len(app.SyncQueues.Queues["stantdard-testing"].Messages) == 1 {
		t.Fatal("there should be 2 messages in queue")
	}
}

func TestSendMessage_POST_DuplicatationDisabledOnFifoQueue(t *testing.T) {
	done := make(chan struct{}, 0)
	go PeriodicTasks(1*time.Second, done)

	// create a queue
	req, err := http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	form := url.Values{}
	form.Add("Action", "CreateQueue")
	form.Add("QueueName", "no-dup-testing.fifo")
	form.Add("Version", "2012-11-05")
	req.PostForm = form

	rr := httptest.NewRecorder()
	http.HandlerFunc(CreateQueue).ServeHTTP(rr, req)

	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got \n%v want %v",
			status, http.StatusOK)
	}

	req, err = http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	form = url.Values{}
	form.Add("Action", "SendMessage")
	form.Add("QueueUrl", "http://localhost:4100/queue/no-dup-testing.fifo")
	form.Add("MessageBody", "Test1")
	form.Add("MessageDeduplicationId", "123")
	form.Add("Version", "2012-11-05")
	req.PostForm = form

	rr = httptest.NewRecorder()
	http.HandlerFunc(SendMessage).ServeHTTP(rr, req)

	// Check the status code is what we expect.
	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got \n%v want %v",
			status, http.StatusOK)
	}
	if len(app.SyncQueues.Queues["no-dup-testing.fifo"].Messages) == 0 {
		t.Fatal("there should be 1 message in queue")
	}

	form = url.Values{}
	form.Add("Action", "SendMessage")
	form.Add("QueueUrl", "http://localhost:4100/queue/no-dup-testing.fifo")
	form.Add("MessageBody", "Test2")
	form.Add("MessageDeduplicationId", "123")
	form.Add("Version", "2012-11-05")
	req.PostForm = form

	rr = httptest.NewRecorder()
	http.HandlerFunc(SendMessage).ServeHTTP(rr, req)

	// Check the status code is what we expect.
	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got \n%v want %v",
			status, http.StatusOK)
	}
	if len(app.SyncQueues.Queues["no-dup-testing.fifo"].Messages) != 2 {
		t.Fatal("there should be 2 message in queue")
	}
}

func TestSendMessage_POST_DuplicatationEnabledOnFifoQueue(t *testing.T) {
	done := make(chan struct{}, 0)
	go PeriodicTasks(1*time.Second, done)

	// create a queue
	req, err := http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	form := url.Values{}
	form.Add("Action", "CreateQueue")
	form.Add("QueueName", "dup-testing.fifo")
	form.Add("Version", "2012-11-05")
	req.PostForm = form

	rr := httptest.NewRecorder()
	http.HandlerFunc(CreateQueue).ServeHTTP(rr, req)

	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got \n%v want %v",
			status, http.StatusOK)
	}

	req, err = http.NewRequest("POST", "/", nil)
	if err != nil {
		t.Fatal(err)
	}

	app.SyncQueues.Queues["dup-testing.fifo"].EnableDuplicates = true

	form = url.Values{}
	form.Add("Action", "SendMessage")
	form.Add("QueueUrl", "http://localhost:4100/queue/dup-testing.fifo")
	form.Add("MessageBody", "Test1")
	form.Add("MessageDeduplicationId", "123")
	form.Add("Version", "2012-11-05")
	req.PostForm = form

	rr = httptest.NewRecorder()
	http.HandlerFunc(SendMessage).ServeHTTP(rr, req)

	// Check the status code is what we expect.
	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got \n%v want %v",
			status, http.StatusOK)
	}
	if len(app.SyncQueues.Queues["dup-testing.fifo"].Messages) == 0 {
		t.Fatal("there should be 1 message in queue")
	}

	form = url.Values{}
	form.Add("Action", "SendMessage")
	form.Add("QueueUrl", "http://localhost:4100/queue/dup-testing.fifo")
	form.Add("MessageBody", "Test2")
	form.Add("MessageDeduplicationId", "123")
	form.Add("Version", "2012-11-05")
	req.PostForm = form

	rr = httptest.NewRecorder()
	http.HandlerFunc(SendMessage).ServeHTTP(rr, req)

	// Check the status code is what we expect.
	if status := rr.Code; status != http.StatusOK {
		t.Errorf("handler returned wrong status code: got \n%v want %v",
			status, http.StatusOK)
	}
	if len(app.SyncQueues.Queues["dup-testing.fifo"].Messages) != 1 {
		t.Fatal("there should be 1 message in queue")
	}
	if body := app.SyncQueues.Queues["dup-testing.fifo"].Messages[0].MessageBody; string(body) == "Test2" {
		t.Fatal("duplicate message should not be added to queue")
	}
}

// waitTimeout waits for the waitgroup for the specified max timeout.
// Returns true if waiting timed out.
// credits: https://stackoverflow.com/questions/32840687/timeout-for-waitgroup-wait
func waitTimeout(wg *sync.WaitGroup, timeout time.Duration) bool {
	c := make(chan struct{})
	go func() {
		defer close(c)
		wg.Wait()
	}()
	select {
	case <-c:
		return false // completed normally
	case <-time.After(timeout):
		return true // timed out
	}
}


text:
<?php

namespace Ekyna\Bundle\MailingBundle\Provider;

use Symfony\Component\Form\FormView;

/**
 * Class RecipientProviderView
 * @package Ekyna\Bundle\MailingBundle\Provider
 * @author Étienne Dauvergne <contact@ekyna.com>
 */
class RecipientProviderView
{
    /**
     * @var string
     */
    private $name;

    /**
     * @var string
     */
    private $label;

    /**
     * @var string
     */
    private $template;

    /**
     * @var FormView
     */
    private $form;

    /**
     * Constructor.
     *
     * @param RecipientProviderInterface $provider
     */
    public function __construct(RecipientProviderInterface $provider)
    {
        $this->name     = $provider->getName();
        $this->label    = $provider->getLabel();
        $this->template = $provider->getFormTemplate();
        $this->form     = $provider->getForm()->createView();
    }

    /**
     * Returns the name.
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Returns the label.
     *
     * @return string
     */
    public function getLabel()
    {
        return $this->label;
    }

    /**
     * Returns the template.
     *
     * @return string
     */
    public function getTemplate()
    {
        return $this->template;
    }

    /**
     * Returns the form.
     *
     * @return FormView
     */
    public function getForm()
    {
        return $this->form;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.assertj.core.api.atomic.boolean_;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.error.ShouldHaveValue.shouldHaveValue;
import static org.assertj.core.util.FailureMessages.actualIsNull;

import java.util.concurrent.atomic.AtomicBoolean;

import org.assertj.core.test.ExpectedException;
import org.junit.Rule;
import org.junit.Test;

public class AtomicBooleanAssert_isFalse_Test {

  @Rule
  public ExpectedException thrown = ExpectedException.none();

  @Test
  public void should_pass_when_actual_value_is_false() {
    AtomicBoolean actual = new AtomicBoolean(false);
    assertThat(actual).isFalse();
  }

  @Test
  public void should_fail_when_actual_value_is_false() {
    AtomicBoolean actual = new AtomicBoolean(true);
    thrown.expectAssertionError(shouldHaveValue(actual, false).create());
    assertThat(actual).isFalse();
  }

  @Test
  public void should_fail_when_actual_is_null() {
    thrown.expectAssertionError(actualIsNull());
    AtomicBoolean actual = null;
    assertThat(actual).isFalse();
  }

}


text:
Static typed facade for [IndexedDB](https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API) with simple API.

## IndexedDB Structure

- **Database** contains named Stores
- - **Store** contains Documents by primary keys and named Indexes
- - - **Document** contains any data
- - - **Index** points to Documents

## DB life Cycle

### DB Schema Example

```typescript
type ACME = {
	Users: {
		Key: number
		Doc: {
			name: {
				first: string
				last: string
			}
			age: number
		}
		Indexes: {
			names: [ string, string ]
			ages: [ number ]
		}
	}
	Articles: {
		Key: string
		Doc: {
			title: string
			content: string
		}
		Indexes: {
			full: [ string, string ]
		}
	}
}
```

### Open DB without Migrations

```typescript
const db = await $$.$mol_db< ACME >( 'ACME' )
```

### Open DB with automatic migrations

```typescript
const db = await $$.$mol_db< ACME >( 'ACME',
	mig => mig.store_make( 'Users' ),
	mig => mig.stores.Users.index_make( 'ages', [ 'age' ] ),
	mig => mig.stores.Users.index_make( 'names', [ 'name.first', 'name.last' ], !!'unique' ),
	mig => mig.store_make( 'Articles' ),
	mig => mig.stores.Articles.index_make( 'full', [ 'title', 'content' ] ),
	// mig => mig.stores.Articles.index_drop( 'full' ),
	// mig => mig.store_drop( 'Articles' ),
)
```

There is 5 migrations. And DB version is 6. After uncommenting last 2 rows, it applies 2 additional migrations and DB version will be 8.

### Close DB Connection

```typescript
db.destructor()
```

### Delete DB

```typescript
db.kill()
```

## Transaction Life Cycle

### Read Only Transactions

```typescript
const { Users, Articles } = db.read( 'Users', 'Articles' )
```

### Read/Write Trasactions

```typescript
const trans = db.change( 'Users', 'Articles' )
const { Users, Articles } = trans.stores

// ...

trans.abort()
// or
await trans.commit()
```

Uncommited transaction without errors will be commitetd automatically. Any modification error aborts transaction.

## Documents Life Cycle

### By Primary key

#### Insert with Auto Incremental Primary Key

```typescript
const key = await Users.put({
	first: 'Jin',
	last: 'Nin',
	age: 36,
})
```

#### Put/Overwrite by Primary Key

```typescript
await Users.put( {
	first: 'Jin',
	last: 'Nin',
	age: 37,
}, 1 )
```

### Get One By Primary Key

```typescript
const user = await Users.get( 1 )
```

### Select 10 By Primary Keys

```typescript
const users = await Users.get( IDBKeyRange.bound( 10, 50 ), 10 )
```

### Count By Primary Keys

```typescript
const count = await Users.count( IDBKeyRange.bound( 10, 50 ) )
```

### By Index

```typescript
const { names, ages } = users.indexes
```

### Get One By Index

```typescript
const user = await names.get([ 'Jin', 'Nin' ])
```

### Select 10 By Index

```typescript
const users = await ages.get( [ 18 ], 10 )
```

### Count By Primary Keys

```typescript
const count = await Users.count([ 18 ])
```

## Usage from NPM

```
npm install mol_db
```

[![](https://badgen.net/bundlephobia/minzip/mol_db)](https://bundlephobia.com/package/mol_db)

```javascript
import { $mol_db } from 'mol_db'
```


text:
title: "0.28 changelog"
description: "Release notes for Sensu Core and Sensu Enterprise releases based
  on Sensu Core version 0.28.x"
version: 0.28
weight: 5
---

# Changelog

## Releases

- [Enterprise 2.5.2 Release Notes](#enterprise-v2-5-2)
- [Enterprise 2.5.1 Release Notes](#enterprise-v2-5-1)
- [Enterprise 2.5.0 Release Notes](#enterprise-v2-5-0)
- [Core 0.28.5 Release Notes](#core-v0-28-5)
- [Core 0.28.4 Release Notes](#core-v0-28-4)
- [Core 0.28.3 Release Notes](#core-v0-28-3)
- [Core 0.28.2 Release Notes](#core-v0-28-2)
- [Core 0.28.1 Release Notes](#core-v0-28-1)
- [Core 0.28.0 Release Notes](#core-v0-28-0)

## Enterprise 2.5.2 Release Notes {#enterprise-v2-5-2}

**March 24, 2017** — Sensu Enterprise version 2.5.2 has been
	released and is available for immediate download. Please note the
	following improvements:

### CHANGES {#enterprise-v2-5-2-changes}

- **IMPROVEMENT**: Built on Sensu Core 0.28.5.

- **IMPROVEMENT**: Improved OpsGenie integration API request debug
	logging.

## Enterprise 2.5.1 Release Notes {#enterprise-v2-5-1}

**March 13, 2017** — Sensu Enterprise version 2.5.1 has been
	released and is available for immediate download. Please note the
	following improvements:

### CHANGES {#enterprise-v2-5-1-changes}

- **IMPROVEMENT**: Built on Sensu Core 0.28.4.

## Enterprise 2.5.0 Release Notes {#enterprise-v2-5-0}

**February 24, 2017** — Sensu Enterprise version 2.5.0 has been
	released and is available for immediate download. Please note the
	following improvements:

### CHANGES {#enterprise-v2-5-0-changes}

- **IMPROVEMENT**: Built on Sensu Core 0.28.0.

- **IMPROVEMENT**: Added OpenTSDB integration `prefix_source` and `prefix`
	options.

- **BUGFIX**: Contact routing array values now properly override the
	configured default/global integration values.

## Core 0.28.5 Release Notes {#core-v0-28-5}

**March 23, 2017** — Sensu Core version 0.28.5 has been released and
	is available for immediate download. Please note the following
	changes:

- **BUGFIX**: Fixed check `subdue` and filter `when` features when a time
	window spans over `00:00:00`, crossing the day boundary.

## Core 0.28.4 Release Notes {#core-v0-28-4}

**March 10, 2017** — Sensu Core version 0.28.4 has been released and
	is available for immediate download. Please note the following
	changes:

- **BUGFIX**: In the interest of addressing a regression causing duplicate
	check execution requests, code added in 0.28.0 to account for task
	scheduling drift has been removed.

## Core 0.28.3 Release Notes {#core-v0-28-3}

**March 9, 2017** — Sensu Core version 0.28.3 has been released and
	is available for immediate download. Please note the following
	changes:

- **BUGFIX**: The Sensu client now includes check source when tracking in
	progress check executions. These changes are necessary to allow
	the Sensu client to execute on several concurrent proxy check
	requests.

## Core 0.28.2 Release Notes {#core-v0-28-2}

**March 6, 2017** — Sensu Core version 0.28.2 has been released
  and is available for immediate download. Please note the following
  changes:

- **BUGFIX**: Clients created via /clients API endpoint now have a
  per-client subscription added automatically, ensuring they can be
  silenced.

## Core 0.28.1 Release Notes {#core-v0-28-1}

**March 2, 2017** — Sensu Core version 0.28.1 has been released
  and is available for immediate download. Please note the following
  changes:

- **BUGFIX**: Check requests with proxy_requests attributes are no
  longer overridden by local check definitions.

- **IMPROVEMENT**: Updated [Oj][3] (used by the sensu-json library) to the
  latest release (2.18.1) for Ruby 2.4 compatibility.

- **IMPROVEMENT**: Updated embedded OpenSSL from [1.0.2j to 1.0.2k][4].

## Core 0.28.0 Release Notes {#core-v0-28-0}

Source: [GitHub.com][2]

**February 23, 2017** — Sensu Core version 0.28.0 has been released
	and is available for immediate download. Please note the following
	improvements:

### CHANGES {#core-v0-28-0-changes}

- **IMPROVEMENT**: Added proxy check requests to improve Sensu's ability
	to monitor external resources that have an associated Sensu proxy
	client. Publish a check request to the configured `subscribers`
	(e.g. `["round-robin:snmp_pollers"]`) for every Sensu client in
	the registry that matches the configured client attributes in
	`client_attributes` on the configured `interval` (e.g. `60`).
	Client tokens in the check definition (e.g. `"check-snmp-if.rb -h
	:::address::: -i eth0"`) are substituted prior to publishing the
	check request. The check request check source is set to the client
	name.

- **IMPROVEMENT**: Schedule check requests and standalone executions with
	the Cron syntax.

- **IMPROVEMENT**: Added the Sensu server registry, containing information
	about the running Sensu servers. Information about the Sensu
	servers is now accessible via the Sensu API /info endpoint.

- **IMPROVEMENT**: Added two optional attributes to Sensu API POST
	/request, "reason" and "creator", for additional context. The
	check request reason and creator are added to the check request
	payload under "api_requested" and become part of the check result.

- **IMPROVEMENT**: Added event IDs to event handler log events for
	additional context, making it easier to trace an event through the
	Sensu pipeline.

- **BUGFIX**: The Sensu interval timers, used for scheduling tasks, now
	account for drift. The check request and standalone execution
	scheduler timers are now more accurate.

- **BUGFIX**: Fixed a bug in the Sensu deep_merge() method that was
	responsible for mutating arrays of the original provided objects.

[1]: https://github.com/sensu/sensu/blob/master/CHANGELOG.md
[2]: https://github.com/sensu/sensu/blob/master/CHANGELOG.md#0280---2017-02-23
[3]: https://github.com/ohler55/oj
[4]: https://www.openssl.org/news/openssl-1.0.2-notes.html


text:
extern "C" {
#include "user_interface.h"
}
#endif
#include "DYStoreConfig.h"

#define DYWIFI_STATE_DISCONNECT 1
#define DYWIFI_STATE_RECONNECT 2
//callback

typedef void (*DYWifiStateCallback)(int);
typedef void (*DYWifiTaskSchdule)(int);			//TaskSchdule time of 01,10,20,40 second

typedef enum {
    DW_NO_SHIELD        = 255,   // for compatibility with WiFi Shield library
    DW_IDLE_STATUS      = 0,
    DW_NO_SSID_AVAIL    = 1,
    DW_SCAN_COMPLETED   = 2,
    DW_CONNECTED        = 3,
    DW_CONNECT_FAILED   = 4,
    DW_CONNECTION_LOST  = 5,
    DW_DISCONNECTED     = 6,
    DW_CONNECTING		= 7
} dw_status_t;

class DYWiFiConfig {
	public:
	DYWiFiConfig();
	virtual ~DYWiFiConfig() {}
	void begin(ESP8266WebServer *server, const char *webbase);
	void begin(ESP8266WebServer *server, const char *webPath, DYWIFICONFIG_STRUCT defaultConfig);
	void handle();
 	template <class T> int read(int address, T &data);			//address of 0 ~ 300
	template <class T> int write(int address, const T &data);	//address of 0 ~ 300
	void commit();
	void setAP(const char *name,const char *password);
	void setHOSTNAME(const char *name);
	void enableAP();
	void disableAP();
	void enableAP(const char *name,const char *password);
	void autoEnableAP(int pin);
	void reConnect();									//set pin to -1 to disable
	void setWifiStateCallback(DYWifiStateCallback cb);
	void setWifiTaskSchduleCallback(DYWifiTaskSchdule cb);
	void setWebReturnPath(const char *path);
	bool setDefaultConfig(DYWIFICONFIG_STRUCT s);
	DYWIFICONFIG_STRUCT createConfig();
	DYWIFICONFIG_STRUCT_PTR getConfig();
	//
	dw_status_t status();
	void printStatus();
	private:
	DYStoreConfig _storeconfig;
	DYWIFICONFIG_STRUCT_PTR _defaultconfig;
	ESP8266WebServer *_server;
	String _scanAPsWebOptionCache;
	String _apname;
	String _appassword;
	String _webPath;
	String _webReturnPath;
	DYWIFICONFIG_STRUCT _dws;
	int _wifiStateMachine = 0;
	//
	long _taskStartTime = 0;
	long _taskEndTime = 0;
	int _taskTimerCounter = 0;
	int _taskState = 0;
	int _nextTaskState = 0;
	long _task10SecondBase = 10;
	long _task20SecondBase = 20;
	long _task40SecondBase = 40;
	long _taskClearCounter;
	int _wifiReconnectCount = 0;
	//
	int _autoEnableAPPin = -1;
	int _wifiStatus = DW_IDLE_STATUS;
	DYWifiStateCallback wifiStateCB;
	DYWifiTaskSchdule	wifiTaskSchdule;
	//
	void init();
	//
	bool autoConnectToAP();
	// void createWebServer(const char *webbase);
	void scanAPs(void);
	 void sendHtmlPageWithRedirectByTimer(String gotoUrl,String Message);
	bool setDHCP(byte isAuto);
	int setWifi(String essid, String epassword);
	void setupWeb();
	void createWebServer();
	void taskSchdule();
	void taskSchdule01Second();
	void taskSchdule10Second();
	void taskSchdule20Second();
	void taskSchdule40Second();
	 //
	void pageOfAdmin();
	void pageOfSetting();
	void pageOfReconnect();
	//
	int mathGCD(int m, int n);
	int mathLCM(int m, int n);

};
#endif


text:
include_recipe "munin::client"

file "#{node['munin']['basedir']}/plugin-conf.d/fail2ban" do
  owner "root"
  group "root"
  mode 644

  content "[fail2ban]\nuser root\n"
end

munin_plugin "fail2ban" do
  create_file true
  cookbook "fail2ban-local"
end


text:
static const char* SAVE_PATH = "downloads/content/";

std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {
    std::stringstream ss(s);
    std::string item;
    std::string buf;
    while (std::getline(ss, item, delim)) {
      if (item[item.length() - 1] == '\\') {
        buf += item.substr(0, item.length() - 1) + delim;
      } else {
        buf += item;
        elems.push_back(buf);
        buf.clear();
      }
    }
    return elems;
}

std::vector<std::string> split(const std::string &s, char delim) {
    std::vector<std::string> elems;
    split(s, delim, elems);
    return elems;
}


text:
import { SettingsManager } from './settings';

const codeLineClass = 'code-line';

export interface CodeLineElement {
	element: HTMLElement;
	line: number;
}

const getCodeLineElements = (() => {
	let cachedElements: CodeLineElement[] | undefined;
	let cachedVersion = -1;
	return (documentVersion: number) => {
		if (!cachedElements || documentVersion !== cachedVersion) {
			cachedVersion = documentVersion;
			cachedElements = [{ element: document.body, line: 0 }];
			for (const element of document.getElementsByClassName(codeLineClass)) {
				const line = +element.getAttribute('data-line')!;
				if (isNaN(line)) {
					continue;
				}

				if (element.tagName === 'CODE' && element.parentElement && element.parentElement.tagName === 'PRE') {
					// Fenched code blocks are a special case since the `code-line` can only be marked on
					// the `<code>` element and not the parent `<pre>` element.
					cachedElements.push({ element: element.parentElement as HTMLElement, line });
				} else if (element.tagName === 'UL' || element.tagName === 'OL') {
					// Skip adding list elements since the first child has the same code line (and should be preferred)
				} else {
					cachedElements.push({ element: element as HTMLElement, line });
				}
			}
		}
		return cachedElements;
	};
})();

/**
 * Find the html elements that map to a specific target line in the editor.
 *
 * If an exact match, returns a single element. If the line is between elements,
 * returns the element prior to and the element after the given line.
 */
export function getElementsForSourceLine(targetLine: number, documentVersion: number): { previous: CodeLineElement; next?: CodeLineElement } {
	const lineNumber = Math.floor(targetLine);
	const lines = getCodeLineElements(documentVersion);
	let previous = lines[0] || null;
	for (const entry of lines) {
		if (entry.line === lineNumber) {
			return { previous: entry, next: undefined };
		} else if (entry.line > lineNumber) {
			return { previous, next: entry };
		}
		previous = entry;
	}
	return { previous };
}

/**
 * Find the html elements that are at a specific pixel offset on the page.
 */
export function getLineElementsAtPageOffset(offset: number, documentVersion: number): { previous: CodeLineElement; next?: CodeLineElement } {
	const lines = getCodeLineElements(documentVersion);
	const position = offset - window.scrollY;
	let lo = -1;
	let hi = lines.length - 1;
	while (lo + 1 < hi) {
		const mid = Math.floor((lo + hi) / 2);
		const bounds = getElementBounds(lines[mid]);
		if (bounds.top + bounds.height >= position) {
			hi = mid;
		}
		else {
			lo = mid;
		}
	}
	const hiElement = lines[hi];
	const hiBounds = getElementBounds(hiElement);
	if (hi >= 1 && hiBounds.top > position) {
		const loElement = lines[lo];
		return { previous: loElement, next: hiElement };
	}
	if (hi > 1 && hi < lines.length && hiBounds.top + hiBounds.height > position) {
		return { previous: hiElement, next: lines[hi + 1] };
	}
	return { previous: hiElement };
}

function getElementBounds({ element }: CodeLineElement): { top: number; height: number } {
	const myBounds = element.getBoundingClientRect();

	// Some code line elements may contain other code line elements.
	// In those cases, only take the height up to that child.
	const codeLineChild = element.querySelector(`.${codeLineClass}`);
	if (codeLineChild) {
		const childBounds = codeLineChild.getBoundingClientRect();
		const height = Math.max(1, (childBounds.top - myBounds.top));
		return {
			top: myBounds.top,
			height: height
		};
	}

	return myBounds;
}

/**
 * Attempt to reveal the element for a source line in the editor.
 */
export function scrollToRevealSourceLine(line: number, documentVersion: number, settingsManager: SettingsManager) {
	if (!settingsManager.settings?.scrollPreviewWithEditor) {
		return;
	}

	if (line <= 0) {
		window.scroll(window.scrollX, 0);
		return;
	}

	const { previous, next } = getElementsForSourceLine(line, documentVersion);
	if (!previous) {
		return;
	}
	let scrollTo = 0;
	const rect = getElementBounds(previous);
	const previousTop = rect.top;
	if (next && next.line !== previous.line) {
		// Between two elements. Go to percentage offset between them.
		const betweenProgress = (line - previous.line) / (next.line - previous.line);
		const previousEnd = previousTop + rect.height;
		const betweenHeight = next.element.getBoundingClientRect().top - previousEnd;
		scrollTo = previousEnd + betweenProgress * betweenHeight;
	} else {
		const progressInElement = line - Math.floor(line);
		scrollTo = previousTop + (rect.height * progressInElement);
	}
	scrollTo = Math.abs(scrollTo) < 1 ? Math.sign(scrollTo) : scrollTo;
	window.scroll(window.scrollX, Math.max(1, window.scrollY + scrollTo));
}

export function getEditorLineNumberForPageOffset(offset: number, documentVersion: number) {
	const { previous, next } = getLineElementsAtPageOffset(offset, documentVersion);
	if (previous) {
		const previousBounds = getElementBounds(previous);
		const offsetFromPrevious = (offset - window.scrollY - previousBounds.top);
		if (next) {
			const progressBetweenElements = offsetFromPrevious / (getElementBounds(next).top - previousBounds.top);
			return previous.line + progressBetweenElements * (next.line - previous.line);
		} else {
			const progressWithinElement = offsetFromPrevious / (previousBounds.height);
			return previous.line + progressWithinElement;
		}
	}
	return null;
}

/**
 * Try to find the html element by using a fragment id
 */
export function getLineElementForFragment(fragment: string, documentVersion: number): CodeLineElement | undefined {
	return getCodeLineElements(documentVersion).find((element) => {
		return element.element.id === fragment;
	});
}


text:
"""module to build fixed flat files"""
import inspect
from collections import defaultdict

from pyFixedFlatFile.exceptions import LineIdentifierException, ParamsException

class PyFixedFlatFile:
    """Implements the logic to build a flat file"""

    def __init__(self, *args, **kwargs):
        """
        Parameters:
            NL (str): line break
            start (int): start position of the line identifier
            stop (int): stop position of the line identifier
            identifier_name (str): This is MANDATORY to write the flat file.
        """

        self.data = defaultdict(list)
        self.nl = '\r\n' if kwargs.get('NL') == 'dos' else '\n'

        # File specification don't initialize a line indexed by zero
        self.position = slice(kwargs.get('start')-1, kwargs.get('stop') -
                              1) if kwargs.get('start') and kwargs.get('start') else slice(0, 1)
        self.identifier_name = kwargs.get('identifier_name', None)

        self.__current_id = None  # identifier of the line
        self.__start_column = 0
        self.__identifier_position = 0  # used in generate file from list of tuples data

    def eq(self, id):
        """Set line ident"""

        self.__current_id = str(id)
        self.__start_column = 0

    def read_to_dict(self, file_path):
        return self._read(file_path, self._process_line_to_dict)

    def read_to_tuple(self, file_path):
        return self._read(file_path, self._process_line_to_tuple)

    def generate_from_dict(self, registros):
        return self.generate(registros, self._generate_from_dict)

    def generate_from_tuple(self, registros):
        return self.generate(registros, self._generate_from_tuple)

    def generate(self, registros, generate_function):
        s = ""
        for registro in registros:
            row_str = generate_function(registro) + "{}".format(self.nl)
            s += row_str

        return s

    def fmt(self, spec, value):
        result = ""
        ident = spec['ident']
        size = spec['size']

        if ident == 'constant':
            # the size will be used as constant value
            result = str(size)
        else:
            if 'fmt_w' in spec:
                resp = spec['fmt_w'](value)
            elif ident == 'filler':
                resp = ' '
            else:
                resp = value

            if 'tp' in spec:
                # Put zeros in string's left
                resp = ('{0:.2f}'.format(resp)).replace(
                    '.', '') if isinstance(resp, float) else resp
                result = '{:0>{size}}'.format(int(resp), size=size)
            else:
                result = '{:<{size}}'.format(resp, size=size)

            if len(result) != size:
                raise Exception("The length of value returned by function is not equal the size! Value return ed: {}, size value {}. the size must be {}".format(
                    resp, size, len(resp)))
        return result

    def _read(self, file_path, process_line):
        result = []
        with open(file_path, 'r') as file_:
            for line in file_:
                result.append(self._process_line(line, process_line))
        return result

    def _process_line(self, line, process_line):
        line_id = line[self.position]
        if line_id not in list(self.data.keys()):
            raise LineIdentifierException(
                f"Line identifier not in specification: {self.data.keys()}")

        reg_spec = self.data[line_id]
        line_result = process_line(reg_spec, line)

        return line_result

    def _process_line_to_dict(self, reg_spec, line):
        line_result = {}
        for spec in reg_spec:
            _, resp = self._process_column(spec, line, line_result)
            line_result.update(resp)
        return line_result

    def _process_line_to_tuple(self, reg_spec, line):
        line_result = []
        aux = {}
        for spec in reg_spec:
            resp, dict_resp = self._process_column(spec, line, aux)
            line_result.append(resp)
            aux.update(dict_resp)
        return tuple(line_result)

    def _process_column(self, spec, line, line_dict):
        ident = spec['ident']
        size = spec['size']
        if ident == 'constant':
            size = len(size)

        param = line[spec['slice']].strip()
        if 'fmt_r' in spec:
            if len(inspect.signature(spec['fmt_r']).parameters) == 1:
                param = spec['fmt_r'](param)
            else:
                param = spec['fmt_r'](param, line_dict)

        if 'tp' in spec:
            param = spec['tp'](param)

        return param, {ident: param}

    def _generate_from_dict(self, registro):
        s = ""
        if self.identifier_name in registro and self.data.get(registro[self.identifier_name], None):
            reg_spec = self.data[registro[self.identifier_name]]
            for spec, value in zip(reg_spec, registro.values()):
                s += self.fmt(spec, value)
        else:
            raise Exception("Id is not in attributes specification!")

        return s

    def _generate_from_tuple(self, registro):
        s = ""
        if self.data.get(registro[self.__identifier_position], None):
            reg_spec = self.data[registro[self.__identifier_position]]
            for spec, value in zip(reg_spec, registro):
                s += self.fmt(spec, value)
        else:
            raise Exception("Id is not in attributes specification!")

        return s

    def builder_data(self, size, **kwargs):
        """Builds the dict with the attributes of the specification.
        This dict will be used for generate method from PyFixedFlatFile generate linha of the flat file.
        """

        if not self.__current_id:
            raise Exception(
                "Id of line not especified: You must use 'eq' method of PyFixedFlatFile!")

        if kwargs['ident'] != 'constant' and not isinstance(size, int):
            raise ParamsException(
                "Size must be a int! Error in {} attribute.".format(kwargs['ident']))

        if ('tp' in kwargs) and (not any((kwargs['tp'] is int, kwargs['tp'] is float))):
            raise ParamsException(
                "tp value must be only 'numeric'! Error in {} attribute.".format(kwargs['ident']))

        if 'fmt' in kwargs and not callable(kwargs['fmt']):
            raise ParamsException(
                "fmt value must be only a callable! Error in {} attribute.".format(kwargs['ident']))

        try:
             kwargs['size'] = int(
                 size) if kwargs['ident'] != 'constant' else size
        except Exception as e:
            raise Exception(
                "size attribute must be int but its value has type {}".format(type(size)))

        kwargs['slice'] = slice(self.__start_column,
                                self.__start_column+kwargs['size'])
        self.__start_column += kwargs['size']
        self.data[self.__current_id].append(kwargs)

        if kwargs['ident'] == self.identifier_name:
            self.__identifier_position = len(self.data[self.__current_id]) - 1

    def __getattr__(self, class_name):
        """implementation of builder pattern that turn possible write code like this:
        builder = PyFixedFlatFile()
        builder.eq("10")
        cnpj(14, fmt=lambda v: "{:>14}".format(v)).\
        inscricaoEstadual(14, default='').\
        """

        def builder(size, **kwargs):
            kwargs.update({'ident': class_name})
            self.builder_data(size, **kwargs)

            return self
        return builder

    def to_csv(self, file_to_read, csv_file_name='csv_file'):
        result = self.read(file_to_read)
        import csv

        with open('{}.csv'.format(csv_file_name), 'w', newline='') as csvfile:
            for row in result:
                writer = csv.DictWriter(csvfile, fieldnames=row.keys())
                writer.writerow(row)


text:
'use strict';
// Select all links with hashes
$('a[href*="#"]')
  // Remove links that don't actually link to anything
  .not('[href="#"]')
  .not('[href="#0"]')
  .click(function(event) {
    // On-page links
    if (
      location.pathname.replace(/^\//, '') === this.pathname.replace(/^\//, '') &&
      location.hostname === this.hostname
    ) {
      // Figure out element to scroll to
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
      // Does a scroll target exist?
      if (target.length) {
        // Only prevent default if animation is actually gonna happen
        event.preventDefault();
        $('html, body').animate({
          scrollTop: target.offset().top - 80
        }, 850, function() {
          // Callback after animation
          // Must change focus!
          var $target = $(target);
          $target.focus();
          if ($target.is(":focus")) { // Checking if the target was focused
            return false;
          } else {
            $target.attr('tabindex', '-1'); // Adding tabindex for elements not focusable
            $target.focus(); // Set focus again
          }
        });
      }
    }
  });

// SMOOTH SCROLLING (with negative scroll of 40 for header)

// $(function() {
//   $('a[href*="#"]:not([href="#"])').click(function() {
//     if (location.pathname.replace(/^\//, '') === this.pathname.replace(/^\//, '') && location.hostname === this.hostname) {
//       var target = $(this.hash);
//       target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
//       if (target.length) {
//         $('html,body').animate({
//           scrollTop: (target.offset().top - 40)
//         }, 850);
//         return false;
//       }
//     }
//   });
// });


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Orbital7.MyGames
{
    public delegate void DeviceSyncEngineProgressDelegate(DeviceSyncEngineProgress updatedProgress);

    public abstract class DeviceSyncEngine
    {
        protected IAccessProvider AccessProvider { get; set; }

        protected int Index { get; set; }

        protected Catalog Catalog { get; set; }

        protected Device Device { get; set; }

        protected bool Cancel { get; set; }

        private void Clear()
        {
            this.Catalog = null;
            this.Device = null;
            this.Index = 0;
            this.Cancel = false;
        }

        public async Task LoadAsync(Catalog catalog, Device device)
        {
            // Clear.
            Clear();

            // Validate.
            await ValidateAsync(catalog, device);

            // Validate complete, record.
            this.Catalog = catalog;
            this.Device = device;
        }

        protected abstract Task ValidateAsync(Catalog catalog, Device device);

        public async Task StartSyncAsync()
        {
            // Ensure device exists.
            if (this.Device == null)
                throw new Exception("No device has been loaded into the Device Sync Engine");

            // Sync.
            await SyncAsync();
        }

        protected abstract Task SyncAsync();

        public void StopSync()
        {
            this.Cancel = true;
        }

        protected void NotifyProgress(DeviceSyncEngineProgressDelegate progress, string description)
        {
            progress?.Invoke(new DeviceSyncEngineProgress()
            {
                GameListIndex = this.Index,
                GameListsCount = this.Catalog.GameLists.Count,
                Description = description,
            });
        }

        protected void NotifySyncComplete(DeviceSyncEngineProgressDelegate progress)
        {
            NotifyProgress(progress, "\nSYNC COMPLETE");
        }

        protected void DeleteGameFiles(string platformFolderPath, string imagesFolderPath, string filename)
        {
            // Delete game files (could be more than one).
            var deviceGameFilePaths = Directory.GetFiles(platformFolderPath,
                Path.GetFileNameWithoutExtension(filename) + ".*");
            foreach (var deviceGameFilePath in deviceGameFilePaths)
                File.Delete(deviceGameFilePath);

            // Delete game config files (should only be one, or not exist at all).
            var deviceGameConfigFilePath = Path.Combine(platformFolderPath, filename + ".cfg");
            if (File.Exists(deviceGameConfigFilePath))
                File.Delete(deviceGameConfigFilePath);

            // Delete game image file (should only be one, but we don't know the extension).
            var deviceImageFilePaths = Directory.GetFiles(imagesFolderPath,
                Game.GetImageFilenameWithoutExtension(filename) + ".*");
            foreach (var deviceImageFilePath in deviceImageFilePaths)
                File.Delete(deviceImageFilePath);
        }
    }
}


text:
/* Author: Ioan Sucan */

#ifndef MOVEIT_OCCUPANCY_MAP_MONITOR_LAZY_FREE_SPACE_UPDATER_
#define MOVEIT_OCCUPANCY_MAP_MONITOR_LAZY_FREE_SPACE_UPDATER_

#include <moveit/occupancy_map_monitor/occupancy_map.h>
#include <boost/thread.hpp>
#include <deque>

namespace occupancy_map_monitor
{
class LazyFreeSpaceUpdater
{
public:
  LazyFreeSpaceUpdater(const OccMapTreePtr& tree, unsigned int max_batch_size = 10);
  ~LazyFreeSpaceUpdater();

  void pushLazyUpdate(octomap::KeySet* occupied_cells, octomap::KeySet* model_cells,
                      const octomap::point3d& sensor_origin);

private:
#ifdef __APPLE__
  typedef std::unordered_map<octomap::OcTreeKey, unsigned int, octomap::OcTreeKey::KeyHash> OcTreeKeyCountMap;
#else
  typedef std::tr1::unordered_map<octomap::OcTreeKey, unsigned int, octomap::OcTreeKey::KeyHash> OcTreeKeyCountMap;
#endif

  void pushBatchToProcess(OcTreeKeyCountMap* occupied_cells, octomap::KeySet* model_cells,
                          const octomap::point3d& sensor_origin);

  void lazyUpdateThread();
  void processThread();

  OccMapTreePtr tree_;
  bool running_;
  std::size_t max_batch_size_;
  double max_sensor_delta_;

  std::deque<octomap::KeySet*> occupied_cells_sets_;
  std::deque<octomap::KeySet*> model_cells_sets_;
  std::deque<octomap::point3d> sensor_origins_;
  boost::condition_variable update_condition_;
  boost::mutex update_cell_sets_lock_;

  OcTreeKeyCountMap* process_occupied_cells_set_;
  octomap::KeySet* process_model_cells_set_;
  octomap::point3d process_sensor_origin_;
  boost::condition_variable process_condition_;
  boost::mutex cell_process_lock_;

  boost::thread update_thread_;
  boost::thread process_thread_;
};
}

#endif /* MOVEIT_OCCUPANCY_MAP_UPDATER_H_ */


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable disable

using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Remote;
using Microsoft.CodeAnalysis.Serialization;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using Xunit;

namespace Microsoft.CodeAnalysis.UnitTests.Diagnostics
{
    public class TestDiagnosticAnalyzerDriver
    {
        private readonly DiagnosticAnalyzerService _diagnosticAnalyzerService;
        private readonly bool _includeSuppressedDiagnostics;

        public TestDiagnosticAnalyzerDriver(Workspace workspace, Project project, bool includeSuppressedDiagnostics = false)
        {
            Assert.IsType<MockDiagnosticUpdateSourceRegistrationService>(((IMefHostExportProvider)workspace.Services.HostServices).GetExportedValue<IDiagnosticUpdateSourceRegistrationService>());
            _diagnosticAnalyzerService = Assert.IsType<DiagnosticAnalyzerService>(((IMefHostExportProvider)workspace.Services.HostServices).GetExportedValue<IDiagnosticAnalyzerService>());
            _diagnosticAnalyzerService.CreateIncrementalAnalyzer(project.Solution.Workspace);
            _includeSuppressedDiagnostics = includeSuppressedDiagnostics;
        }

        private async Task<IEnumerable<Diagnostic>> GetDiagnosticsAsync(
            Project project,
            Document document,
            TextSpan? filterSpan,
            bool getDocumentDiagnostics,
            bool getProjectDiagnostics)
        {
            var documentDiagnostics = SpecializedCollections.EmptyEnumerable<Diagnostic>();
            var projectDiagnostics = SpecializedCollections.EmptyEnumerable<Diagnostic>();

            if (getDocumentDiagnostics)
            {
                var dxs = await _diagnosticAnalyzerService.GetDiagnosticsAsync(project.Solution, project.Id, document.Id, _includeSuppressedDiagnostics);
                documentDiagnostics = await CodeAnalysis.Diagnostics.Extensions.ToDiagnosticsAsync(
                    filterSpan is null
                        ? dxs.Where(d => d.HasTextSpan)
                        : dxs.Where(d => d.HasTextSpan && d.GetTextSpan().IntersectsWith(filterSpan.Value)),
                    project,
                    CancellationToken.None);
            }

            if (getProjectDiagnostics)
            {
                var dxs = await _diagnosticAnalyzerService.GetDiagnosticsAsync(project.Solution, project.Id, includeSuppressedDiagnostics: _includeSuppressedDiagnostics);
                projectDiagnostics = await CodeAnalysis.Diagnostics.Extensions.ToDiagnosticsAsync(dxs.Where(d => !d.HasTextSpan), project, CancellationToken.None);
            }

            var allDiagnostics = documentDiagnostics.Concat(projectDiagnostics);

            if (!_includeSuppressedDiagnostics)
            {
                Assert.True(!allDiagnostics.Any(d => d.IsSuppressed));
            }

            return allDiagnostics;
        }

        public Task<IEnumerable<Diagnostic>> GetAllDiagnosticsAsync(Document document, TextSpan? filterSpan)
            => GetDiagnosticsAsync(document.Project, document, filterSpan, getDocumentDiagnostics: true, getProjectDiagnostics: true);

        public async Task<IEnumerable<Diagnostic>> GetAllDiagnosticsAsync(Project project)
        {
            var diagnostics = new List<Diagnostic>();
            foreach (var document in project.Documents)
            {
                var span = (await document.GetSyntaxRootAsync()).FullSpan;
                var documentDiagnostics = await GetDocumentDiagnosticsAsync(document, span);
                diagnostics.AddRange(documentDiagnostics);
            }

            var projectDiagnostics = await GetProjectDiagnosticsAsync(project);
            diagnostics.AddRange(projectDiagnostics);
            return diagnostics;
        }

        public Task<IEnumerable<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, TextSpan span)
            => GetDiagnosticsAsync(document.Project, document, span, getDocumentDiagnostics: true, getProjectDiagnostics: false);

        public Task<IEnumerable<Diagnostic>> GetProjectDiagnosticsAsync(Project project)
            => GetDiagnosticsAsync(project, document: null, filterSpan: null, getDocumentDiagnostics: false, getProjectDiagnostics: true);
    }
}


text:
import * as React from 'react';
import { mount } from 'enzyme';

import { ConceptSetsApi, WorkspacesApi } from 'generated/fetch';

import { ConceptNavigationBar } from 'app/pages/data/concept/concept-navigation-bar';
import { registerApiClient } from 'app/services/swagger-fetch-clients';
import { currentWorkspaceStore } from 'app/utils/navigation';

import { ConceptSetsApiStub } from 'testing/stubs/concept-sets-api-stub';
import { workspaceDataStub } from 'testing/stubs/workspaces';
import { WorkspacesApiStub } from 'testing/stubs/workspaces-api-stub';

describe('ConceptNavigationBar', () => {
  const component = () => {
    return mount(
      <ConceptNavigationBar ns='test' wsId='1' showConcepts={true} />
    );
  };

  beforeEach(() => {
    registerApiClient(WorkspacesApi, new WorkspacesApiStub());
    registerApiClient(ConceptSetsApi, new ConceptSetsApiStub());
    currentWorkspaceStore.next(workspaceDataStub);
  });

  it('should render', () => {
    const wrapper = component();
    expect(wrapper).toBeTruthy();
  });
});


text:
namespace spdlog {
namespace details {
struct null_mutex
{
    void lock() {}
    void unlock() {}
    bool try_lock()
    {
        return true;
    }
};

struct null_atomic_int
{
    int value;
    null_atomic_int() = default;

    explicit null_atomic_int(int val)
        : value(val)
    {}

    int load(std::memory_order) const
    {
        return value;
    }

    void store(int val)
    {
        value = val;
    }
};

} // namespace details
} // namespace spdlog


text:
using System;
using System.Collections;

namespace System.Security.Cryptography {

	public sealed class AsnEncodedDataEnumerator : IEnumerator {

		private AsnEncodedDataCollection _collection;
		private int _position;

		// note: couldn't reuse the IEnumerator from ArrayList because
		// it doesn't throw the same exceptions
		internal AsnEncodedDataEnumerator (AsnEncodedDataCollection collection)
		{
			_collection = collection;
			_position = -1;
		}

		// properties

		public AsnEncodedData Current {
			get {
				if (_position < 0)
					throw new ArgumentOutOfRangeException ();
				return (AsnEncodedData) _collection [_position];
			}
		}

		object IEnumerator.Current {
			get {
				if (_position < 0)
					throw new ArgumentOutOfRangeException ();
				return _collection [_position];
			}
		}

		// methods

		public bool MoveNext ()
		{
			if (++_position < _collection.Count)
				return true;
			else {
				// strangely we must always be able to return the last entry
				_position = _collection.Count - 1;
				return false;
			}
		}

		public void Reset ()
		{
			_position = -1;
		}
	}
}

#endif


text:
<?xml version="1.0" ?>
<config>
    <modules>
        <Aoe_Scheduler>
            <active>true</active>
            <codePool>community</codePool>
        </Aoe_Scheduler>
    </modules>
</config>