测试公开契约
Coddy 面向 Rust 开发者的 Dart 课程的第 41 课,共 48 课。
Rust 的 assert! 在发布版构建中仍然有效,而 debug_assert! 通常取决于构建设置。Dart 断言可能会被禁用,因此必需的探测应使用显式抛出异常。测试公开行为和边界输入,而不是检查源代码或私有字段;Rust 示例特意使用了始终启用的检查。
必需的探测应使用显式抛出异常,因为 Dart 断言可能会被禁用。测试公开行为和边界,而不是检查源代码字符串或私有实现细节。这里展示的 ASCII 检查并未实现 Store 任务。
完整的 Rust 程序:
fn main() { assert!("".is_ascii()); assert!("v2".is_ascii()); assert!("".is_ascii()); assert!(!"".is_ascii()); println!("checks passed"); }
完整的 Dart 程序:
void check(bool ok){if(!ok)throw StateError('failed');}
bool ascii(String s)=>s.codeUnits.every((u)=>u<128);
void main(){check(ascii(''));check(ascii('v2'));check(ascii('\u007f'));check(!ascii('\u0080'));print('checks passed');}挑战
简单实现 Store(int limit),并提供 bool put(String key,int value)、int? get(String key) 和 getter size。只有在容量未满时才能插入新键;即使容量已满,替换已有键也应成功。拒绝操作不得更改内容。输入依次为容量和完整的 key value 键值对;输出为 accepted|size。容量范围为 0 到 100,值为整数。独立探测还会检查存储的值和拒绝行为。
不要在可编辑文件中打印内容。提供的 exercise.dart 会解析输入并返回输出;锁定的驱动程序会独立探测公共 API,并在结果后打印一个换行符。
你的代码写在 Store.dart、exercise.dart 中。main.dart 包含提供的输入输出代码,不能编辑。
亲手试试
import 'dart:io';
import 'dart:convert';
import 'exercise.dart';
import 'Store.dart';
void check(bool condition){if(!condition)throw StateError('Public API contract failed');}
Future<void> main() async {
final raw=await stdin.transform(utf8.decoder).join();
final input=raw.replaceFirst(RegExp(r'\r?\n$'),'');
final s=Store(1);check(s.put('a',2));check(!s.put('b',3)&&s.get('b')==null);check(s.put('a',7)&&s.get('a')==7&&s.size==1);check(!Store(0).put('x',1));
stdout.writeln(solve(input));
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Rust 开发者的 Dart中的所有课
自己练习: Dart 在线编译器