在调用初始化列表之前是否可以断言类构造函数上的参数?
class Foo
{
int m_lower;
int m_upper;
unsigned int m_delta;
public:
Foo(int t_lower, int t_upper) :
assert(t_lower < t_upper), // Assert here, before initialisation of fields.
m_lower(t_lower),
m_upper(t_upper),
m_delta(t_upper - t_lower)
{
// Assert could be made here, but m_delta would have underflowed if t_upper < t_lower.
}
}
Run Code Online (Sandbox Code Playgroud)
在初始化列表之前断言的好处是可以立即提出每个字段的初始化要求,并且不必对具有相同要求的每个初始化进行多次检查。虽然 m_delta 的初始化可以在初始化方法中进行init_delta,但如果多个值具有相同的要求,t_upper > t_lower则必须将断言放置在每个值中(以防先前的断言被删除)。如果放置在构造函数本身中,则一个或多个字段的初始化可能已经失败(出现比下溢更戏剧性的情况)。
如果放置在初始化列表的顶部,则合约在检查时对用户来说是清楚的,并且会在发生任何错误(例如本例中的下溢)之前标记错误。
上述案例只是该问题的一个简化示例。我知道有更好的方法来解决上述特定问题(abs() 等)。
感谢您的帮助和建议!
我对 Spock 不是很熟悉,所以我将不胜感激提供一些提示。我有一个自定义对象列表。我想检查此列表是否包含任意数量的对象,其中某些字段具有精确值。
例如,我有包含 100 条记录的 pojo 和列表
public class CustomObject {
private int id;
private String name;
private double salary;
}
Run Code Online (Sandbox Code Playgroud)
我想检查这样的事情:
List<CustomObject> objects = new ArrayList<>();
assert objects.contains(
object.id==100 && object.salary > 900
)
Run Code Online (Sandbox Code Playgroud)
但“名称”可以是任何。
我正在寻找一种方法(如果可用),它可以比较两个值并在比较失败时引发带有有意义消息的断言错误。
如果我使用assert,则失败消息不包含断言失败时比较的值。
>>> a = 3
>>> b = 4
>>> assert a == b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
>>>
Run Code Online (Sandbox Code Playgroud)
如果我使用包中的assertEqual()方法unittest.TestCase,断言消息将包含比较的值。
a = 3
b = 4
> self.assertEqual(a, b)
E AssertionError: 3 != 4
Run Code Online (Sandbox Code Playgroud)
请注意,这里的断言错误消息包含比较的值。这在现实生活中非常有用,因此对我来说是必要的。平原assert(见上文)不会这样做。
但是,到目前为止,我assertEqual()只能在继承自unittest.TestCase并提供一些其他必需方法的类中使用,例如runTest(). 我想在assertEqual()任何地方使用,而不仅仅是在继承的类中。那可能吗?
我尝试了以下方法,但没有奏效。
>>> import unittest
>>> unittest.TestCase.assertEqual(a, b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module> …Run Code Online (Sandbox Code Playgroud) 我正在尝试验证 cucumberjs / puppeteer 中不存在选择器。如何使用 cucumber-assert 来使用 throws 断言?
我正在研究自动化测试来支持测试 ember 前端应用程序。我正在使用 cucumberjs、puppeteerjs 和 cucumber-assert。
我之前使用过以下内容:
if (await page.waitForSelector('[data-test-text-title-refunded-widget-console="true"]')) {
let textContentOfElement = await page.evaluate(() => document.body.querySelector('[data-test-text-title-refunded-widget-console="true"]').textContent);
return assert.equal(textContentOfElement, widgetTitle, `title with text ${ widgetTitle } is not present`);
}
Run Code Online (Sandbox Code Playgroud)
当我验证元素存在并且文本正确时,它起作用。对于我当前的断言,我使用了 cucumber-assert npm 包中的以下 throws 断言:
assert.throws(someFunctionThatThrows).then(callback);
Run Code Online (Sandbox Code Playgroud)
我不确定如何处理回调函数 - 到目前为止我有以下内容。
const assert = require('cucumber-assert');
return assert.throws(await page.waitForSelector('[data-test-text-title- import-payment-file-widget-console="true"]'))
.then(function(err) {
});
Run Code Online (Sandbox Code Playgroud)
我应该在回调中返回失败吗?
* 更新 * 我相信我找到了一种不同的方法来解决我的问题。这是将来其他人遇到同样问题的情况。
if (await page.$('[data-test-text-title-import-payment-file-widget-console="true"]', { timeout: settings._30000 }) === null) {
return Promise.resolve();
}
return …Run Code Online (Sandbox Code Playgroud) 当使用Java和assertThrows时:
public static <T extends Throwable> T assertThrows(Class<T> expectedType, Executable executable)
Run Code Online (Sandbox Code Playgroud)
我们可以编写简单的 lambda 函数:
@Test
void testExpectedException() {
Assertions.assertThrows(NumberFormatException.class, () -> {
Integer.parseInt("One");
});
}
Run Code Online (Sandbox Code Playgroud)
我们如何在 Groovy 中做到这一点?
我正在尝试类似的事情:
@Test
void testExpectedException() {
assertThrows(NumberFormatException.class, {
Integer.parseInt("One");
}())
}
Run Code Online (Sandbox Code Playgroud)
但错误被抛出并且没有被捕获:
java.lang.format.NumberFormatException: For ....
Run Code Online (Sandbox Code Playgroud) 我正在阅读https://groovy-lang.org/closures.html#this 中的 Groovy 闭包文档。有一个关于 GString 行为的问题。
- GStrings 中的闭包
该文件提到了以下内容:
取以下代码:
def x = 1
def gs = "x = ${x}"
assert gs == 'x = 1'
Run Code Online (Sandbox Code Playgroud)
该代码的行为与您预期的一样,但是如果您添加以下内容会发生什么:
x = 2
assert gs == 'x = 2'
Run Code Online (Sandbox Code Playgroud)
你会看到断言失败了!有两个原因:
GString 只懒惰地评估值的 toString 表示
GString 中的语法 ${x} 不代表闭包,而是 $x 的表达式,在创建 GString 时计算。
在我们的示例中,GString 是使用引用 x 的表达式创建的。创建 GString 时,x 的值为 1,因此创建的 GString 值为 1。触发断言时,评估 GString,并使用 toString 将 1 转换为 String。当我们将 x 更改为 2 时,我们确实更改了 x 的值,但它是一个不同的对象,并且 GString 仍然引用旧的。
如果 GString 引用的值发生变化,它只会更改其 toString …
我在我的 xUnit 测试中使用了优秀的Shouldly库,我发现自己在不同的测试中使用了断言的集合序列,所以我将它们组合成新的断言扩展方法 - 但是当我这样做时,我丢失了Shouldly上下文断言消息。
这是我的旧代码,它Shouldly用于在Shouldly断言错误中包含源级信息和调用站点上下文:
[Fact]
public void Dict_should_contain_valid_Foobar_Bar_entry()
{
IDictionary<String,Bar> dict = ...
dict.TryGetValue( "Foobar", out Bar bar ).ShouldBeTrue();
bar.ShouldNotBeNull();
bar.ChildList.Count.ShouldBe( expected: 3 );
bar.Message.ShouldBeNull();
}
[Fact]
public void Dict_should_contain_valid_Barbaz_Bar_entry()
{
IDictionary<String,Bar> dict = ...
dict.TryGetValue( "Barbaz", out Bar bar ).ShouldBeTrue();
bar.ShouldNotBeNull();
bar.ChildList.Count.ShouldBe( expected: 3 );
bar.Message.ShouldBeNull();
}
Run Code Online (Sandbox Code Playgroud)
我在同一个项目中将它转换为这个新的扩展方法:
public static void ShouldBeValidBar( this IDictionary<String,Bar> dict, String barName )
{
dict.ShouldNotBeNull();
dict.TryGetValue( barName, out Bar bar ).ShouldBeTrue();
bar.ShouldNotBeNull(); …Run Code Online (Sandbox Code Playgroud) 我有 Pandas 数据框,它具有“状态”列的长度。我 100% 确定,该列中所有值的长度都是 2。当我尝试编写断言语句时,出现断言错误。我不确定我是否正确使用了断言语句。请帮忙。
assert df['state'].str.len().all() == 2
Run Code Online (Sandbox Code Playgroud)
我的理解:断言 state 列中的所有值的长度都等于 2。请告诉我这是否正确。谢谢。
contract Sharer {
function sendHalf(address payable addr) public payable returns (uint balance) {
require(msg.value % 2 == 0, "Even value required.");
uint balanceBeforeTransfer = address(this).balance;
addr.transfer(msg.value / 2);
// Since transfer throws an exception on failure and
// cannot call back here, there should be no way for us to
// still have half of the money.
assert(address(this).balance == balanceBeforeTransfer - msg.value / 2);
return address(this).balance;
}
}
Run Code Online (Sandbox Code Playgroud)
对于上述合约,在什么情况下断言失败/address(this).balance 不会减少 (msg.value / 2)?为什么我们需要在这里断言?
听起来像一个明显答案的愚蠢问题:)
我仍然冒险要求加倍确定.
我们确实使用如下所示的断言
ArrayList alProperties = new ArrayList();
assert alProperties != null : "alProperties is null";
Run Code Online (Sandbox Code Playgroud)
问题是在断言上制作一个小而简单的文档是很困难的.有很多关于断言的书籍,但理想情况下,我喜欢给一个新的程序员非常简单的使用类似断言的指南.顺便说一句,像pmd这样的工具检查断言是否正确使用?
提前致谢.
assert ×10
groovy ×2
java ×2
python ×2
unit-testing ×2
c# ×1
c++ ×1
closures ×1
constructor ×1
cucumberjs ×1
dataframe ×1
evm ×1
gstring ×1
javascript ×1
junit ×1
junit5 ×1
new-operator ×1
pandas ×1
puppeteer ×1
shouldly ×1
solidity ×1
spock ×1
tostring ×1
xunit ×1