- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试第一次全神贯注地编写一些单元测试,并且我正在 golang 中为使用 aws lambda 的辅助项目做这件事。
下面是两个文件。main.go
接受一个包含电子邮件地址的事件,并在认知用户池中创建用户。main_test.go
应该模拟 createUser
main.go
中的函数,但是当我尝试运行测试时出现错误。
我刚刚从 instantiating the client globally 切换了我的代码在观看 this youtube video 之后在 aws sdk 接口(interface)上使用指针接收器方法.
main.go
package main
import (
"fmt"
"log"
"os"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
cidp "github.com/aws/aws-sdk-go/service/cognitoidentityprovider"
cidpif "github.com/aws/aws-sdk-go/service/cognitoidentityprovider/cognitoidentityprovideriface"
lib "github.com/sean/repo/lib"
)
type createUserEvent struct {
EmailAddress string `json:"email_address"`
}
type awsService struct {
cidpif.CognitoIdentityProviderAPI
}
func (c *awsService) createUser(e createUserEvent) error {
input := &cidp.AdminCreateUserInput{
UserPoolId: aws.String(os.Getenv("USER_POOL_ID")),
Username: aws.String(e.EmailAddress),
DesiredDeliveryMediums: []*string{aws.String("EMAIL")},
ForceAliasCreation: aws.Bool(true),
UserAttributes: []*cidp.AttributeType{
{
Name: aws.String("email"),
Value: aws.String(e.EmailAddress),
},
},
}
_, err := c.AdminCreateUser(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case cidp.ErrCodeResourceNotFoundException:
log.Printf("[ERROR] %v, %v", cidp.ErrCodeResourceNotFoundException, aerr.Error())
case cidp.ErrCodeInvalidParameterException:
log.Printf("[ERROR] %v, %v", cidp.ErrCodeInvalidParameterException, aerr.Error())
case cidp.ErrCodeUserNotFoundException:
log.Printf("[ERROR] %v, %v", cidp.ErrCodeUserNotFoundException, aerr.Error())
case cidp.ErrCodeUsernameExistsException:
log.Printf("[ERROR] %v, %v", cidp.ErrCodeUsernameExistsException, aerr.Error())
case cidp.ErrCodeInvalidPasswordException:
log.Printf("[ERROR] %v, %v", cidp.ErrCodeInvalidPasswordException, aerr.Error())
case cidp.ErrCodeCodeDeliveryFailureException:
log.Printf("[ERROR] %v, %v", cidp.ErrCodeCodeDeliveryFailureException, aerr.Error())
case cidp.ErrCodeUnexpectedLambdaException:
log.Printf("[ERROR] %v, %v", cidp.ErrCodeUnexpectedLambdaException, aerr.Error())
case cidp.ErrCodeUserLambdaValidationException:
log.Printf("[ERROR] %v, %v", cidp.ErrCodeUserLambdaValidationException, aerr.Error())
case cidp.ErrCodeInvalidLambdaResponseException:
log.Printf("[ERROR] %v, %v", cidp.ErrCodeInvalidLambdaResponseException, aerr.Error())
case cidp.ErrCodePreconditionNotMetException:
log.Printf("[ERROR] %v, %v", cidp.ErrCodePreconditionNotMetException, aerr.Error())
case cidp.ErrCodeInvalidSmsRoleAccessPolicyException:
log.Printf("[ERROR] %v, %v", cidp.ErrCodeInvalidSmsRoleAccessPolicyException, aerr.Error())
case cidp.ErrCodeInvalidSmsRoleTrustRelationshipException:
log.Printf("[ERROR] %v, %v", cidp.ErrCodeInvalidSmsRoleTrustRelationshipException, aerr.Error())
case cidp.ErrCodeTooManyRequestsException:
log.Printf("[ERROR] %v, %v", cidp.ErrCodeTooManyRequestsException, aerr.Error())
case cidp.ErrCodeNotAuthorizedException:
log.Printf("[ERROR] %v, %v", cidp.ErrCodeNotAuthorizedException, aerr.Error())
case cidp.ErrCodeUnsupportedUserStateException:
log.Printf("[ERROR] %v, %v", cidp.ErrCodeUnsupportedUserStateException, aerr.Error())
case cidp.ErrCodeInternalErrorException:
log.Printf("[ERROR] %v, %v", cidp.ErrCodeInternalErrorException, aerr.Error())
default:
log.Printf("[ERROR] %v", err.Error())
}
} else {
log.Printf("[ERROR] %v", err.Error())
}
return err
}
log.Printf("[INFO] Created new user %v successfully", e.EmailAddress)
return nil
}
func (c *awsService) handler(e createUserEvent) (events.APIGatewayProxyResponse, error) {
headers := map[string]string{"Content-Type": "application/json"}
err := c.createUser(e)
if err != nil {
resp := lib.GenerateResponseBody(fmt.Sprintf("Error creating user %v", e.EmailAddress), 404, err, headers)
return resp, nil
}
resp := lib.GenerateResponseBody(fmt.Sprintf("Created new user %v", e.EmailAddress), 200, nil, headers)
return resp, nil
}
func main() {
c := awsService{cidp.New(session.New())}
lambda.Start(c.handler)
}
main_test.go
package main
import (
"os"
"testing"
cidp "github.com/aws/aws-sdk-go/service/cognitoidentityprovider"
cidpif "github.com/aws/aws-sdk-go/service/cognitoidentityprovider/cognitoidentityprovideriface"
)
type mockCreateUser struct {
cidpif.CognitoIdentityProviderAPI
Response cidp.AdminCreateUserOutput
}
func (d mockCreateUser) CreateUser(e createUserEvent) error {
return nil
}
func TestCreateUser(t *testing.T) {
t.Run("Successfully create user", func(t *testing.T) {
m := mockCreateUser{Response: cidp.AdminCreateUserOutput{}}
c := awsService{m}
err := os.Setenv("USER_POOL_ID", "ap-southeast-2_ovum4dzAL")
if err != nil {
t.Fatal(err)
}
err = c.createUser(createUserEvent{EmailAddress: "user@example.com"})
if err != nil {
t.Fatal("User should have been created")
}
})
}
错误
Running tool: /usr/local/go/bin/go test -timeout 30s -run ^TestCreateUser$ github.com/sean/repo/src/create_user
--- FAIL: TestCreateUser (0.00s)
--- FAIL: TestCreateUser/Successfully_create_user (0.00s)
panic: runtime error: invalid memory address or nil pointer dereference [recovered]
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x60 pc=0x137c2f2]
goroutine 6 [running]:
testing.tRunner.func1.1(0x13e00c0, 0x173fd70)
/usr/local/go/src/testing/testing.go:1072 +0x30d
testing.tRunner.func1(0xc000001b00)
/usr/local/go/src/testing/testing.go:1075 +0x41a
panic(0x13e00c0, 0x173fd70)
/usr/local/go/src/runtime/panic.go:969 +0x1b9
github.com/sean/repo/src/create_user.(*mockCreateUser).AdminCreateUser(0xc00000ee40, 0xc00006a200, 0xc00001e39d, 0x18, 0xc0000b24b0)
<autogenerated>:1 +0x32
github.com/sean/repo/src/create_user.(*awsService).createUser(0xc000030738, 0x145bbca, 0x10, 0x18, 0x0)
/Users/sean/code/github/sean/repo/src/create_user/main.go:39 +0x2b7
github.com/sean/repo/src/create_user.TestCreateUser.func1(0xc000001b00)
/Users/sean/code/github/sean/repo/src/create_user/main_test.go:30 +0x10c
testing.tRunner(0xc000001b00, 0x1476718)
/usr/local/go/src/testing/testing.go:1123 +0xef
created by testing.(*T).Run
/usr/local/go/src/testing/testing.go:1168 +0x2b3
FAIL github.com/sean/repo/src/create_user 0.543s
FAIL
最佳答案
我认为这里的问题是,您想模拟 AdminCreateUser()
方法,但实际上模拟了 CreateUser()
方法。
因此,当您创建 mockCreateUser
的新实例时,结构,“实现” cidpif.CognitoIdentityProviderAPI
接口(interface),然后调用AdminCreateUser()
方法,它没有实现并且失败。
您的main_test.go
中的相关代码应该是这样的:
type mockCreateUser struct {
cidpif.CognitoIdentityProviderAPI
Response cidp.AdminCreateUserOutput
}
func (d mockCreateUser) CreateUser(e createUserEvent) error {
return nil
}
添加以下“虚拟”就足够了(并删除
CreateUser()
方法):
func (d mockCreateUser) AdminCreateUser(*cidp.AdminCreateUserInput) (*cidp.AdminCreateUserOutput, error) {
return d.Response, nil
}
awsService
的“应用程序”。 struct,但不实现任何 AWS 接口(interface)。相反,它包含一个
configuration
结构。此配置包含您从环境中读取的值(例如
USER_POOL_ID
、
EMAIL
)以及 AWS 服务的实例。
config
轻松修改方法/函数的输入。的
application
.如果您想在每个测试和不同的行为中使用不同的电子邮件等,您只需更改配置即可。
package main
import (
"os"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cognitoidentityprovider"
"github.com/aws/aws-sdk-go/service/cognitoidentityprovider/cognitoidentityprovideriface"
)
type createUserEvent struct {
EmailAddress string `json:"email_address"`
}
type configuration struct {
poolId string
idp cognitoidentityprovideriface.CognitoIdentityProviderAPI
}
type application struct {
config configuration
}
func (app *application) createUser(event createUserEvent) error {
input := &cognitoidentityprovider.AdminCreateUserInput{
UserPoolId: aws.String(app.config.poolId),
Username: aws.String(event.EmailAddress),
DesiredDeliveryMediums: aws.StringSlice([]string{"EMAIL"}),
ForceAliasCreation: aws.Bool(true),
UserAttributes: []*cognitoidentityprovider.AttributeType{
{
Name: aws.String("email"),
Value: aws.String(event.EmailAddress),
},
},
}
_, err := app.config.idp.AdminCreateUser(input)
if err != nil {
return err
}
return nil
}
func (app *application) handler(event createUserEvent) (events.APIGatewayProxyResponse, error) {
err := app.createUser(event)
if err != nil {
return events.APIGatewayProxyResponse{}, err
}
return events.APIGatewayProxyResponse{}, nil
}
func main() {
config := configuration{
poolId: os.Getenv("USER_POOL_ID"),
idp: cognitoidentityprovider.New(session.Must(session.NewSession())),
}
app := application{config: config}
lambda.Start(app.handler)
}
main_test.go
package main
import (
"testing"
"github.com/aws/aws-sdk-go/service/cognitoidentityprovider"
"github.com/aws/aws-sdk-go/service/cognitoidentityprovider/cognitoidentityprovideriface"
)
type mockAdminCreateUser struct {
cognitoidentityprovideriface.CognitoIdentityProviderAPI
Response *cognitoidentityprovider.AdminCreateUserOutput
Error error
}
func (d mockAdminCreateUser) AdminCreateUser(*cognitoidentityprovider.AdminCreateUserInput) (*cognitoidentityprovider.AdminCreateUserOutput, error) {
return d.Response, d.Error
}
func TestCreateUser(t *testing.T) {
t.Run("Successfully create user", func(t *testing.T) {
idpMock := mockAdminCreateUser{
Response: &cognitoidentityprovider.AdminCreateUserOutput{},
Error: nil,
}
app := application{config: configuration{
poolId: "test",
idp: idpMock,
}}
err := app.createUser(createUserEvent{EmailAddress: "user@example.com"})
if err != nil {
t.Fatal("User should have been created")
}
})
}
关于amazon-web-services - AWS SDK Go Lambda 单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65464240/
我试图要求 test/unit 的新版本(即不是与 ruby 捆绑的版本) .根据 instructions我用 gem i test-unit 安装它.但是现在当我需要 test/unit我似乎
简短版本是: 我有一个 systemd 单元,我想在调用时检查脚本的返回代码: systemctl status service.service 长版本:我有一个 lsb init 脚本正是这样做的,
我正在使用反射动态创建一个类的实例,这工作正常,除非尝试通过单元测试执行此操作 - 我使用的是 MS 测试框架。 我收到熟悉的错误:“无法加载文件或程序集‘Assy’或其依赖项之一。系统找不到指定的文
我想知道测试网站“界面功能”的最佳实践是什么。 我对哪些方法可用于测试界面和动态生成的内容感兴趣。特别是,我很难弄清楚是否可以为需要用户交互的操作创建自动化测试,或者这是否只是浪费时间,我应该让一些
我有一个简单的 Python 服务,其中有一个无限执行某些操作的循环。在各种信号上,sys.exit(0) 被调用,这导致 SystemExit 被引发,然后如果可以的话应该进行一些清理。 在测试中,
我正在使用 OpenCV 2.4.2 这是 OpenCV 文档中的引文 C++: void HoughLinesP(InputArray image, OutputArray lines, doubl
忙于 C# 中的自动化测试用例,我们需要在每次测试后恢复数据库快照。问题是,当运行多个测试时它会失败,因为“其他用户正在使用数据库时无法更改数据库状态。” 我们使用 SqlConnection.Cle
我阅读了 C# 规范并用谷歌搜索了它,但一无所获。 我 99% 肯定 C# 中没有像单元命名空间指令这样的功能,但问题是:为什么?是否有惯用或技术原因? 这很方便,尤其是当我们的大部分文件都由单个命名
我目前正在尝试向我的应用程序(一个非常老的项目......评论说 iOS 2.0)添加单元测试(精确的应用程序测试)并且总是偶然发现 undefined symbols for architectur
我正在使用Delphi 7,并且有一个新单元要在我的项目中使用。我已经编译了新的。当我尝试通过将其添加到uses子句在项目中使用此单元时,出现错误,提示未找到.dcu文件。我还尝试将文件的完整路径放在
场景:我需要编写一个复杂的nHibernate查询,该查询将返回预计的DTO,但是我想使用TDD方法。该方法如下所示: public PrintDTO GetUsersForPrinting(int
您可以通过运行以下命令在事件 html 设置中显示 Jupyter 笔记本: $ jupyter nbconvert untitled.ipynb --to slides --post serve 有
如何在一个网站上拥有多个 AdSense 单元? Google 提供的唯一代码是按单位计算的。 (adsbygoogle = window.adsbygoogle || []).push({})
我刚刚开始为大量代码编写测试。有很多类依赖于文件系统,即读取 CSV 文件、读/写配置文件等。 当前测试文件存储在项目(这是一个 Maven2 项目)的 test 目录中,但由于多种原因该目录并不总是
我对 TDD 还很陌生,在单元测试方面也不是很老练,所以才有这个问题。我有这个用 PHP 编写的遗留函数 function foo(){ x = bar(); y = baz();
我创建了一个程序,在 Swing 窗口的一侧显示结果过滤选项,但默认情况下它们水平相邻显示,这浪费了我在 BorderLayout 的西侧分配的空间。我可以在构造函数或添加语句中传递任何内容来将它们堆
标题不好的借口:如果有人能更好地描述它,请做。 我有一个 WeakList类,它“基本上”是一个 List> (虽然不是字面意义上的派生自列表,但它应该对用户完全透明)。 现在的基本思想是“如果引用的
我正在尝试在 UITableView 上添加两个原型(prototype)单元。但是,我不知道如何验证是否能够为每个原型(prototype)“返回”正确的单元格。你们能帮我一下吗? func ta
我正在使用 CloudKit 作为数据库创建一个简单的待办事项列表应用程序。目前我可以添加和删除对象,但对编辑对象感到困惑。 编辑项目 Controller protocol EditItemCont
我正在针对以下任务训练 RNN:给定一个包含 30 个单词的序列,然后将该序列分类为二进制类。 在我的网络中拥有超过 30 个单元(LSTM、GRU 或普通 RNN)有好处吗?我在网上看到过很多例子,
我是一名优秀的程序员,十分优秀!