当前位置: 首页>>代码示例>>Golang>>正文


Golang log.UseMock函数代码示例

本文整理汇总了Golang中github.com/letsencrypt/boulder/log.UseMock函数的典型用法代码示例。如果您正苦于以下问题:Golang UseMock函数的具体用法?Golang UseMock怎么用?Golang UseMock使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了UseMock函数的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: TestSleepInterval

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())
}
开发者ID:jfrazelle,项目名称:boulder,代码行数:49,代码来源:main_test.go

示例2: setup

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,
	}
}
开发者ID:jfrazelle,项目名称:boulder,代码行数:26,代码来源:main_test.go

示例3: TestCfsslLogger

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()
	}
}
开发者ID:jfrazelle,项目名称:boulder,代码行数:31,代码来源:shell_test.go

示例4: TestMysqlLogger

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()
	}
}
开发者ID:jfrazelle,项目名称:boulder,代码行数:32,代码来源:shell_test.go

示例5: TestGenerateMessage

func TestGenerateMessage(t *testing.T) {
	fc := clock.NewFake()
	stats := metrics.NewNoopScope()
	fromAddress, _ := mail.ParseAddress("happy sender <[email protected]>")
	log := blog.UseMock()
	m := New("", "", "", "", *fromAddress, log, stats, 0, 0)
	m.clk = fc
	m.csprgSource = fakeSource{}
	messageBytes, err := m.generateMessage([]string{"[email protected]"}, "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\" <[email protected]>")
	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: <[email protected]>")
	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")
}
开发者ID:jfrazelle,项目名称:boulder,代码行数:25,代码来源:mailer_test.go

示例6: setup

func setup(t *testing.T) (*MailerImpl, net.Listener, func()) {
	stats := metrics.NewNoopScope()
	fromAddress, _ := mail.ParseAddress("[email protected]")
	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),
		"[email protected]",
		"paswd",
		*fromAddress,
		log,
		stats,
		time.Second*2, time.Second*10)

	return m, l, cleanUp
}
开发者ID:jfrazelle,项目名称:boulder,代码行数:34,代码来源:mailer_test.go

示例7: TestReconnect

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")
	}
}
开发者ID:MTRNord,项目名称:boulder-freifunk_support,代码行数:30,代码来源:connection_test.go

示例8: TestFailNonASCIIAddress

func TestFailNonASCIIAddress(t *testing.T) {
	log := blog.UseMock()
	stats := metrics.NewNoopScope()
	fromAddress, _ := mail.ParseAddress("[email protected]")
	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")
}
开发者ID:jfrazelle,项目名称:boulder,代码行数:8,代码来源:mailer_test.go

示例9: TestResolveEmails

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{
		"[email protected]",
		"[email protected]",
		"[email protected]",
	}

	test.AssertEquals(t, len(destinations), len(expected))
	for i := range expected {
		test.AssertEquals(t, destinations[i], expected[i])
	}
}
开发者ID:jfrazelle,项目名称:boulder,代码行数:52,代码来源:main_test.go

示例10: TestPurgeAuthzs

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))
}
开发者ID:jfrazelle,项目名称:boulder,代码行数:39,代码来源:main_test.go

示例11: TestMessageContent

func TestMessageContent(t *testing.T) {
	// Create a mailer with fixed content
	const (
		testSubject     = "Test Subject"
		testDestination = "[email protected]"
	)
	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])
}
开发者ID:jfrazelle,项目名称:boulder,代码行数:37,代码来源:main_test.go

示例12: TestParseAnswer

	"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")
开发者ID:andrewrothstein,项目名称:boulder,代码行数:31,代码来源:resolver_test.go

示例13: TestMailCheckpointing

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:      "[email protected]",
		Subject: testSubject,
		Body:    string(testBody),
	}, mc.Messages[0])
	test.AssertEquals(t, mocks.MailerMessage{
		To:      "[email protected]",
		Subject: testSubject,
		Body:    string(testBody),
	}, mc.Messages[1])
	test.AssertEquals(t, mocks.MailerMessage{
		To:      "[email protected]",
		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),
	}

//.........这里部分代码省略.........
开发者ID:jfrazelle,项目名称:boulder,代码行数:101,代码来源:main_test.go


注:本文中的github.com/letsencrypt/boulder/log.UseMock函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。