php - 由于从电子邮件中提取的令牌损坏,功能测试失败
问题描述
在 Symfony 5 项目中,当从电子邮件中提取的确认令牌损坏时,用户注册的功能测试会失败。(电子邮件是使用 SwiftMailer 完成的,因为它能够发送日志。)
测试从填写带有用户名和电子邮件地址的表格开始。保存时发送电子邮件。因为测试包括$this->client->followRedirects(false);
测试可以访问电子邮件的内容。当从电子邮件中提取令牌时,它包含额外的字符。所以当测试尝试$this->client->request('GET', '/register/reset/' . $token);
由于无效的注册数据而导致测试失败。
这是测试的一个版本:
public function testReplacementEmail() {
$this->client->clickLink('Staff');
$this->client->clickLink('Replace');
$this->client->followRedirects(false);
$this->client->submitForm('Save', [
'user[fname]' => 'Useless',
'user[sname]' => 'Garbage',
'user[email]' => 'ugar@bogus.info'
]);
$mailCollector = $this->client->getProfile()->getCollector('swiftmailer');
$this->assertSame(1, $mailCollector->getMessageCount());
$collectedMessages = $mailCollector->getMessages();
$message = $collectedMessages[0];
$this->assertStringContainsString('has been asked to designate', $message);
$string = 'register/reset/';
$offset = strlen($string);
$pos = strpos($message, $string) + $offset;
$token = substr($message, $pos, 32);
var_dump($token);
$this->client->followRedirects(true);
$this->client->request('GET', '/logout');
$this->client->request('GET', '/register/reset/' . $token);
$this->client->submitForm('Save', [
'new_password[plainPassword][first]' => '123Abc',
'new_password[plainPassword][second]' => '123Abc',
]);
$this->assertStringContainsString('You are now the registered representative', $this->client->getResponse()->getContent());
}
我已经在处理Replace
链接的控制器中包含了这些行$token = md5(uniqid(rand(), true));var_dump($token);
,以便获得一个纯正的令牌。运行测试时,这些行会产生如下内容:
string(32) "ad47260162194f9ab6deb55eb4f38178"
如果我var_dump($message);
在测试中使用来访问电子邮件的内容,我会看到如下内容:
href="http://localhost/register/reset/ad47260162194f9ab6deb55eb4f38178"
然而,在测试包括的地方,var_dump($token);
我看到的是这样的:
string(32) "7260162194f9ab6d=
eb55eb4f38178"
(在 Windows 系统上)的存在=\r\n
会导致链接失败。
我想知道为什么会出现这些额外的字符,以及如果可能的话如何避免它们。
解决方案
字符串中=\r\n
的 表明该消息是 MIME 编码的,带有引号的可打印并且您的链接跨越行尾。SwiftMailer 消息对象似乎有一个神奇的__toString()
方法(奇怪的是,IMO)产生消息的编码形式。如果您想要原始的原始消息字符串,您可以调用getBody()
消息对象的方法,然后只需strpos()
对结果使用您的测试即可。
推荐阅读
- asp.net-core - ASP.NET Core 中的服务总线
- c# - 检查应用程序路径中的文件 -> 始终返回 false
- ruby - 找不到中间人命令/捆绑器不工作
- html - 如何使用 HTML 和 CSS 来创建倾斜的导航栏设计?
- angular - 当我尝试使用带有 Angular 应用程序的 ckeditor5 构建生产版本时出现错误
- avaudioengine - 淡出 AVAudioEngine AVAudioPlayerNode
- python - 根据 2 个不同的范围生成日期
- java - 使用 BufferedReader 解析文件
- python - 如何遍历特定的列表对 - Python
- android - 如何通过单击recyclerview中的不同项目将一个片段替换为另一个带有Web视图的片段以打开不同的URL?