Skip to content

Commit

Permalink
Simplify test code
Browse files Browse the repository at this point in the history
  • Loading branch information
Fethbita committed Oct 4, 2024
1 parent 3f4265c commit 68e616f
Showing 1 changed file with 31 additions and 35 deletions.
66 changes: 31 additions & 35 deletions src/guide-test-fn-rng.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,54 +40,50 @@ fn main() {
}
```

And as for tests, we can create a MockRng that implements RngCore and CryptoRng and provide a Default implementation with the value we want to return. Notice that the MocRng struct is marked with `#[cfg(test)]` as to not allow tainting the valid usages of the `xor_with_random_bytes` function:
And as for tests, we can create a MockRng that implements RngCore and CryptoRng and provide a Default implementation with the value we want to return:

```rust
#[cfg(test)]
#[derive(Clone, Copy, Debug)]
struct MockRng {
data: [u8; 8],
index: usize,
}
mod tests {
use super::*;

#[cfg(test)]
impl Default for MockRng {
fn default() -> MockRng {
MockRng {
data: *b"\x57\x88\x1e\xed\x1c\x72\x01\xd8",
index: 0,
#[derive(Clone, Copy, Debug)]
struct MockRng {
data: [u8; 8],
index: usize,
}

impl Default for MockRng {
fn default() -> MockRng {
MockRng {
data: *b"\x57\x88\x1e\xed\x1c\x72\x01\xd8",
index: 0,
}
}
}
}

#[cfg(test)]
impl CryptoRng for MockRng {}
impl CryptoRng for MockRng {}

#[cfg(test)]
impl RngCore for MockRng {
fn next_u32(&mut self) -> u32 {
unimplemented!()
}
impl RngCore for MockRng {
fn next_u32(&mut self) -> u32 {
unimplemented!()
}

fn next_u64(&mut self) -> u64 {
unimplemented!()
}
fn next_u64(&mut self) -> u64 {
unimplemented!()
}

fn fill_bytes(&mut self, dest: &mut [u8]) {
for byte in dest.iter_mut() {
*byte = self.data[self.index];
self.index = (self.index + 1) % self.data.len();
fn fill_bytes(&mut self, dest: &mut [u8]) {
for byte in dest.iter_mut() {
*byte = self.data[self.index];
self.index = (self.index + 1) % self.data.len();
}
}
}

fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand::Error> {
unimplemented!()
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand::Error> {
unimplemented!()
}
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_xor_with_mock_rng() {
Expand Down

0 comments on commit 68e616f

Please sign in to comment.