Пример #1
0
func TestSleepInterval(t *testing.T) {
	const sleepLen = 10
	const numMessages = 3
	mc := &mocks.Mailer{}
	dbMap := mockEmailResolver{}

	testDestinationsBody, err := ioutil.ReadFile("testdata/test_msg_recipients.txt")
	test.AssertNotError(t, err, "failed to read testdata/test_msg_recipients.txt")

	// Set up a mock mailer that sleeps for `sleepLen` seconds
	m := &mailer{
		log:           blog.UseMock(),
		mailer:        mc,
		emailTemplate: "",
		sleepInterval: sleepLen * time.Second,
		checkpoint:    interval{start: 0, end: numMessages},
		clk:           newFakeClock(t),
		destinations:  testDestinationsBody,
		dbMap:         dbMap,
	}

	// Call run() - this should sleep `sleepLen` per destination address
	// After it returns, we expect (sleepLen * number of destinations) seconds has
	// elapsed
	err = m.run()
	test.AssertNotError(t, err, "error calling mailer run()")
	expectedEnd := newFakeClock(t)
	expectedEnd.Add(time.Second * time.Duration(sleepLen*numMessages))
	test.AssertEquals(t, m.clk.Now(), expectedEnd.Now())

	// Set up a mock mailer that doesn't sleep at all
	m = &mailer{
		log:           blog.UseMock(),
		mailer:        mc,
		emailTemplate: "",
		sleepInterval: 0,
		checkpoint:    interval{start: 0, end: 3},
		clk:           newFakeClock(t),
		destinations:  testDestinationsBody,
		dbMap:         dbMap,
	}

	// Call run() - this should blast through all destinations without sleep
	// After it returns, we expect no clock time to have elapsed on the fake clock
	err = m.run()
	test.AssertNotError(t, err, "error calling mailer run()")
	expectedEnd = newFakeClock(t)
	test.AssertEquals(t, m.clk.Now(), expectedEnd.Now())
}
Пример #2
0
func setup(t *testing.T) testCtx {
	log := blog.UseMock()

	// Using DBConnSAFullPerms to be able to insert registrations and certificates
	dbMap, err := sa.NewDbMap(vars.DBConnSAFullPerms, 0)
	if err != nil {
		t.Fatalf("Couldn't connect the database: %s", err)
	}
	cleanUp := test.ResetSATestDatabase(t)

	fc := newFakeClock(t)
	ssa, err := sa.NewSQLStorageAuthority(dbMap, fc, log)
	if err != nil {
		t.Fatalf("unable to create SQLStorageAuthority: %s", err)
	}

	return testCtx{
		c: contactExporter{
			dbMap: dbMap,
			log:   log,
			clk:   fc,
		},
		ssa:     ssa,
		cleanUp: cleanUp,
	}
}
Пример #3
0
func TestCfsslLogger(t *testing.T) {
	log := blog.UseMock()
	cLog := cfsslLogger{log}

	testCases := []struct {
		msg, expected string
	}{
		{
			"",
			"ERR: [AUDIT] ",
		},
		{
			"Test",
			"ERR: [AUDIT] Test",
		},
	}

	for _, tc := range testCases {
		// cfsslLogger proxies blog.AuditLogger to provide Crit() and Emerg()
		// methods that are expected by CFSSL's logger
		cLog.Crit(tc.msg)
		cLog.Emerg(tc.msg)
		logged := log.GetAll()
		// Calling Crit and Emerg should produce two AuditErr outputs matching the
		// testCase expected output
		test.AssertEquals(t, len(logged), 2)
		test.AssertEquals(t, logged[0], tc.expected)
		test.AssertEquals(t, logged[1], tc.expected)
		log.Clear()
	}
}
Пример #4
0
func TestMysqlLogger(t *testing.T) {
	log := blog.UseMock()
	mLog := mysqlLogger{log}

	testCases := []struct {
		args     []interface{}
		expected string
	}{
		{
			[]interface{}{nil},
			`ERR: [AUDIT] [mysql] <nil>`,
		},
		{
			[]interface{}{""},
			`ERR: [AUDIT] [mysql] `,
		},
		{
			[]interface{}{"Sup ", 12345, " Sup sup"},
			`ERR: [AUDIT] [mysql] Sup 12345 Sup sup`,
		},
	}

	for _, tc := range testCases {
		// mysqlLogger proxies blog.AuditLogger to provide a Print() method
		mLog.Print(tc.args...)
		logged := log.GetAll()
		// Calling Print should produce the expected output
		test.AssertEquals(t, len(logged), 1)
		test.AssertEquals(t, logged[0], tc.expected)
		log.Clear()
	}
}
Пример #5
0
func TestGenerateMessage(t *testing.T) {
	fc := clock.NewFake()
	stats := metrics.NewNoopScope()
	fromAddress, _ := mail.ParseAddress("happy sender <*****@*****.**>")
	log := blog.UseMock()
	m := New("", "", "", "", *fromAddress, log, stats, 0, 0)
	m.clk = fc
	m.csprgSource = fakeSource{}
	messageBytes, err := m.generateMessage([]string{"*****@*****.**"}, "test subject", "this is the body\n")
	test.AssertNotError(t, err, "Failed to generate email body")
	message := string(messageBytes)
	fields := strings.Split(message, "\r\n")
	test.AssertEquals(t, len(fields), 12)
	fmt.Println(message)
	test.AssertEquals(t, fields[0], "To: \"[email protected]\"")
	test.AssertEquals(t, fields[1], "From: \"happy sender\" <*****@*****.**>")
	test.AssertEquals(t, fields[2], "Subject: test subject")
	test.AssertEquals(t, fields[3], "Date: 01 Jan 70 00:00 UTC")
	test.AssertEquals(t, fields[4], "Message-Id: <*****@*****.**>")
	test.AssertEquals(t, fields[5], "MIME-Version: 1.0")
	test.AssertEquals(t, fields[6], "Content-Type: text/plain; charset=UTF-8")
	test.AssertEquals(t, fields[7], "Content-Transfer-Encoding: quoted-printable")
	test.AssertEquals(t, fields[8], "")
	test.AssertEquals(t, fields[9], "this is the body")
}
Пример #6
0
func setup(t *testing.T) (*MailerImpl, net.Listener, func()) {
	stats := metrics.NewNoopScope()
	fromAddress, _ := mail.ParseAddress("*****@*****.**")
	log := blog.UseMock()

	// Listen on port 0 to get any free available port
	l, err := net.Listen("tcp", ":0")
	if err != nil {
		t.Fatalf("listen: %s", err)
	}
	cleanUp := func() {
		err := l.Close()
		if err != nil {
			t.Errorf("listen.Close: %s", err)
		}
	}

	// We can look at the listener Addr() to figure out which free port was
	// assigned by the operating system
	addr := l.Addr().(*net.TCPAddr)
	port := addr.Port

	m := New(
		"localhost",
		fmt.Sprintf("%d", port),
		"*****@*****.**",
		"paswd",
		*fromAddress,
		log,
		stats,
		time.Second*2, time.Second*10)

	return m, l, cleanUp
}
func TestReconnect(t *testing.T) {
	ac, mockChannel, finish := setup(t)
	defer finish()

	// Override the clock so the sleep calls are instantaneous, regardless of what
	// the retry calls say.
	ac.clk = clock.NewFake()
	ac.retryTimeoutBase = time.Second
	ac.retryTimeoutMax = time.Second

	mockChannel.EXPECT().QueueDeclare(
		"fooqueue", AmqpDurable, AmqpDeleteUnused, AmqpExclusive, AmqpNoWait, nil).AnyTimes()
	mockChannel.EXPECT().QueueBind("fooqueue", "fooqueue", AmqpExchange, false, nil).Times(3).Return(errors.New("fail"))
	mockChannel.EXPECT().QueueBind("fooqueue", "fooqueue", AmqpExchange, false, nil).Return(nil)
	mockChannel.EXPECT().Consume("fooqueue", consumerName, AmqpAutoAck, AmqpExclusive, AmqpNoLocal, AmqpNoWait, nil).Return(make(<-chan amqp.Delivery), nil)
	mockChannel.EXPECT().NotifyClose(gomock.Any()).Return(make(chan *amqp.Error))

	log = blog.UseMock()

	ac.reconnect(&cmd.AMQPConfig{}, log)
	if ac.channel != mockChannel {
		t.Errorf("ac.channel was not equal to mockChannel")
	}
	if ac.msgs == nil {
		t.Errorf("ac.msgs was not initialized")
	}
	if ac.closeChan == nil {
		t.Errorf("ac.closeChan was not initialized")
	}
}
Пример #8
0
func TestFailNonASCIIAddress(t *testing.T) {
	log := blog.UseMock()
	stats := metrics.NewNoopScope()
	fromAddress, _ := mail.ParseAddress("*****@*****.**")
	m := New("", "", "", "", *fromAddress, log, stats, 0, 0)
	_, err := m.generateMessage([]string{"遗憾@email.com"}, "test subject", "this is the body\n")
	test.AssertError(t, err, "Allowed a non-ASCII to address incorrectly")
}
Пример #9
0
func TestResolveEmails(t *testing.T) {
	// Start with three reg. IDs. Note: the IDs have been matched with fake
	// results in the `db` slice in `mockEmailResolver`'s `SelectOne`. If you add
	// more test cases here you must also add the corresponding DB result in the
	// mock.
	regs := []regID{
		{
			ID: 1,
		},
		{
			ID: 2,
		},
		{
			ID: 3,
		},
		// This registration ID deliberately doesn't exist in the mock data to make
		// sure this case is handled gracefully
		{
			ID: 999,
		},
	}
	contactsJSON, err := json.Marshal(regs)
	test.AssertNotError(t, err, "failed to marshal test regs")

	dbMap := mockEmailResolver{}
	mc := &mocks.Mailer{}
	m := &mailer{
		log:           blog.UseMock(),
		mailer:        mc,
		dbMap:         dbMap,
		subject:       "Test",
		destinations:  contactsJSON,
		emailTemplate: "Hi",
		checkpoint:    interval{start: 0},
		sleepInterval: 0,
		clk:           newFakeClock(t),
	}

	destinations, err := m.resolveDestinations()
	test.AssertNotError(t, err, "failed to resolveDestinations")

	expected := []string{
		"*****@*****.**",
		"*****@*****.**",
		"*****@*****.**",
	}

	test.AssertEquals(t, len(destinations), len(expected))
	for i := range expected {
		test.AssertEquals(t, destinations[i], expected[i])
	}
}
Пример #10
0
func TestPurgeAuthzs(t *testing.T) {
	dbMap, err := sa.NewDbMap(vars.DBConnSAFullPerms, 0)
	if err != nil {
		t.Fatalf("Couldn't connect the database: %s", err)
	}
	log := blog.UseMock()
	fc := clock.NewFake()
	fc.Add(time.Hour)
	ssa, err := sa.NewSQLStorageAuthority(dbMap, fc, log)
	if err != nil {
		t.Fatalf("unable to create SQLStorageAuthority: %s", err)
	}
	cleanUp := test.ResetSATestDatabase(t)
	defer cleanUp()
	stats := metrics.NewNoopScope()

	p := expiredAuthzPurger{stats, log, fc, dbMap, 1}

	rows, err := p.purgeAuthzs(time.Time{}, true)
	test.AssertNotError(t, err, "purgeAuthzs failed")
	test.AssertEquals(t, rows, int64(0))

	old, new := fc.Now().Add(-time.Hour), fc.Now().Add(time.Hour)

	reg := satest.CreateWorkingRegistration(t, ssa)
	_, err = ssa.NewPendingAuthorization(context.Background(), core.Authorization{RegistrationID: reg.ID, Expires: &old})
	test.AssertNotError(t, err, "NewPendingAuthorization failed")
	_, err = ssa.NewPendingAuthorization(context.Background(), core.Authorization{RegistrationID: reg.ID, Expires: &old})
	test.AssertNotError(t, err, "NewPendingAuthorization failed")
	_, err = ssa.NewPendingAuthorization(context.Background(), core.Authorization{RegistrationID: reg.ID, Expires: &new})
	test.AssertNotError(t, err, "NewPendingAuthorization failed")

	rows, err = p.purgeAuthzs(fc.Now(), true)
	test.AssertNotError(t, err, "purgeAuthzs failed")
	test.AssertEquals(t, rows, int64(2))
	rows, err = p.purgeAuthzs(fc.Now().Add(time.Hour), true)
	test.AssertNotError(t, err, "purgeAuthzs failed")
	test.AssertEquals(t, rows, int64(1))
}
Пример #11
0
func TestMessageContent(t *testing.T) {
	// Create a mailer with fixed content
	const (
		testSubject     = "Test Subject"
		testDestination = "*****@*****.**"
	)
	testDestinationsBody, err := ioutil.ReadFile("testdata/test_msg_recipients.txt")
	test.AssertNotError(t, err, "failed to read testdata/test_msg_recipients.txt")

	testBody, err := ioutil.ReadFile("testdata/test_msg_body.txt")
	test.AssertNotError(t, err, "failed to read testdata/test_msg_body.txt")

	dbMap := mockEmailResolver{}
	mc := &mocks.Mailer{}
	m := &mailer{
		log:           blog.UseMock(),
		mailer:        mc,
		dbMap:         dbMap,
		subject:       testSubject,
		destinations:  testDestinationsBody,
		emailTemplate: string(testBody),
		checkpoint:    interval{start: 0, end: 1},
		sleepInterval: 0,
		clk:           newFakeClock(t),
	}

	// Run the mailer, one message should have been created with the content
	// expected
	err = m.run()
	test.AssertNotError(t, err, "error calling mailer run()")
	test.AssertEquals(t, len(mc.Messages), 1)
	test.AssertEquals(t, mocks.MailerMessage{
		To:      testDestination,
		Subject: testSubject,
		Body:    string(testBody),
	}, mc.Messages[0])
}
Пример #12
0
	"net/url"
	"sync"
	"testing"
	"time"

	"github.com/miekg/dns"
	"golang.org/x/net/context"

	"github.com/letsencrypt/boulder/core"
	blog "github.com/letsencrypt/boulder/log"
	"github.com/letsencrypt/boulder/metrics"
	"github.com/letsencrypt/boulder/mocks"
	"github.com/letsencrypt/boulder/test"
)

var log = blog.UseMock()

func TestParseAnswer(t *testing.T) {
	as := []core.GPDNSAnswer{
		{"a", 257, 10, "0 issue \"ca.com\""},
		{"b", 1, 10, "1.1.1.1"},
	}

	r, err := parseAnswer(as)
	test.AssertNotError(t, err, "Failed to parse records")
	test.AssertEquals(t, len(r), 1)
	test.AssertEquals(t, r[0].Hdr.Name, "a.")
	test.AssertEquals(t, r[0].Hdr.Ttl, uint32(10))
	test.AssertEquals(t, r[0].Flag, uint8(0))
	test.AssertEquals(t, r[0].Tag, "issue")
	test.AssertEquals(t, r[0].Value, "ca.com")
Пример #13
0
func TestMailCheckpointing(t *testing.T) {
	const testSubject = "Test Subject"
	dbMap := mockEmailResolver{}

	testDestinationsBody, err := ioutil.ReadFile("testdata/test_msg_recipients.txt")
	test.AssertNotError(t, err, "failed to read testdata/test_msg_recipients.txt")

	testBody, err := ioutil.ReadFile("testdata/test_msg_body.txt")
	test.AssertNotError(t, err, "failed to read testdata/test_msg_body.txt")
	mc := &mocks.Mailer{}

	// Create a mailer with a checkpoint interval larger than the number of
	// destinations
	m := &mailer{
		log:           blog.UseMock(),
		mailer:        mc,
		dbMap:         dbMap,
		subject:       testSubject,
		destinations:  testDestinationsBody,
		emailTemplate: string(testBody),
		checkpoint:    interval{start: 99999, end: 900000},
		sleepInterval: 0,
		clk:           newFakeClock(t),
	}

	// Run the mailer. It should produce an error about the interval start
	mc.Clear()
	err = m.run()
	test.AssertEquals(t, len(mc.Messages), 0)
	test.AssertEquals(t, err.Error(), "interval start value (99999) is greater than number of destinations (7)")

	// Create a mailer with a negative sleep interval
	m = &mailer{
		log:           blog.UseMock(),
		mailer:        mc,
		dbMap:         dbMap,
		subject:       testSubject,
		destinations:  testDestinationsBody,
		emailTemplate: string(testBody),
		checkpoint:    interval{},
		sleepInterval: -10,
		clk:           newFakeClock(t),
	}

	// Run the mailer. It should produce an error about the sleep interval
	mc.Clear()
	err = m.run()
	test.AssertEquals(t, len(mc.Messages), 0)
	test.AssertEquals(t, err.Error(), "sleep interval (-10) is < 0")

	// Create a mailer with a checkpoint interval starting after 4 destinations from
	// the start of the file
	m = &mailer{
		log:           blog.UseMock(),
		mailer:        mc,
		dbMap:         dbMap,
		subject:       testSubject,
		destinations:  testDestinationsBody,
		emailTemplate: string(testBody),
		checkpoint:    interval{start: 4},
		sleepInterval: 0,
		clk:           newFakeClock(t),
	}

	// Run the mailer. Three messages should have been produced, one to
	// you'[email protected] (id 5 of the fake DB), one to
	// [email protected] (id 6), and one to [email protected] (id 4).
	mc.Clear()
	err = m.run()
	test.AssertNotError(t, err, "run() produced an error")
	test.AssertEquals(t, len(mc.Messages), 3)
	test.AssertEquals(t, mocks.MailerMessage{
		To:      "*****@*****.**",
		Subject: testSubject,
		Body:    string(testBody),
	}, mc.Messages[0])
	test.AssertEquals(t, mocks.MailerMessage{
		To:      "*****@*****.**",
		Subject: testSubject,
		Body:    string(testBody),
	}, mc.Messages[1])
	test.AssertEquals(t, mocks.MailerMessage{
		To:      "*****@*****.**",
		Subject: testSubject,
		Body:    string(testBody),
	}, mc.Messages[2])

	// Create a mailer with a checkpoint interval ending after 3 destinations
	m = &mailer{
		log:           blog.UseMock(),
		mailer:        mc,
		dbMap:         dbMap,
		subject:       testSubject,
		destinations:  testDestinationsBody,
		emailTemplate: string(testBody),
		checkpoint:    interval{end: 3},
		sleepInterval: 0,
		clk:           newFakeClock(t),
	}

	// Run the mailer. Three messages should have been produced, one to
	// [email protected] (ID 1), one to [email protected] (ID 2),
	// and one to [email protected] (ID 3)
	mc.Clear()
	err = m.run()
	test.AssertNotError(t, err, "run() produced an error")
	test.AssertEquals(t, len(mc.Messages), 3)
	test.AssertEquals(t, mocks.MailerMessage{
		To:      "*****@*****.**",
		Subject: testSubject,
		Body:    string(testBody),
	}, mc.Messages[0])
	test.AssertEquals(t, mocks.MailerMessage{
		To:      "*****@*****.**",
		Subject: testSubject,
		Body:    string(testBody),
	}, mc.Messages[1])
	test.AssertEquals(t, mocks.MailerMessage{
		To:      "*****@*****.**",
		Subject: testSubject,
		Body:    string(testBody),
	}, mc.Messages[2])

	// Create a mailer with a checkpoint interval covering 2 destinations from the
	// middle of the file
	m = &mailer{
		log:           blog.UseMock(),
		mailer:        mc,
		dbMap:         dbMap,
		subject:       testSubject,
		destinations:  testDestinationsBody,
		emailTemplate: string(testBody),
		checkpoint:    interval{start: 3, end: 5},
		sleepInterval: 0,
		clk:           newFakeClock(t),
	}

	// Run the mailer. Two messages should have been produced, one to
	// [email protected] (ID 4) and another
	// one destined to [email protected] (ID 5)
	mc.Clear()
	err = m.run()
	test.AssertNotError(t, err, "run() produced an error")
	test.AssertEquals(t, len(mc.Messages), 2)
	test.AssertEquals(t, mocks.MailerMessage{
		To:      "*****@*****.**",
		Subject: testSubject,
		Body:    string(testBody),
	}, mc.Messages[0])
	test.AssertEquals(t, mocks.MailerMessage{
		To:      "*****@*****.**",
		Subject: testSubject,
		Body:    string(testBody),
	}, mc.Messages[1])

}