Added a test for write_history

This commit is contained in:
Justine 2022-12-07 10:23:46 +01:00
parent e770d7cb18
commit 8a2b1f7cce
2 changed files with 23 additions and 11 deletions

View File

@ -18,7 +18,8 @@ Later, I can even make something useful out of it. For example, I could make it
* Tests for this history system
# Todo
* Other tests for the rest of the features (add test for write_history_line)
* Add a function that gets the path of the history file, rather than copying it every time
* Other tests for the rest of the features
* Add a builtin history command
* Add a builtin !<number> like in bash
* Get some sleep

View File

@ -99,7 +99,7 @@ fn process_line(input: String) -> bool {
return false;
}
fn write_to_history(command: &str, number: &i32) -> Result<(), std::io::Error> {
fn write_to_history(command: &str) -> Result<(), std::io::Error> {
//Write a command to history
let filepath = dirs::home_dir().unwrap().join("history.rshell");
let mut file = OpenOptions::new()
@ -108,6 +108,12 @@ fn write_to_history(command: &str, number: &i32) -> Result<(), std::io::Error> {
.create(true)
.open(&filepath)
.unwrap();
let number = match get_history_number() {
Ok(n) => n + 1,
Err(_) => 1
};
writeln!(file, "{} {}", number, command.trim())?;
return Ok(())
}
@ -119,7 +125,6 @@ fn get_history_number() -> Result<i32, std::io::Error> {
let mut reader = BufReader::new(file).lines();
let myline = String::from(reader.last().unwrap()?);
let mut number = myline.split(' ').next().expect("???").parse().unwrap();
//number = number + 1;
return Ok(number);
}
@ -153,12 +158,7 @@ fn main(){
let mut input = String::new();
stdin().read_line(&mut input).unwrap();
let number = match get_history_number() {
Ok(n) => n + 1,
Err(_) => 1
};
write_to_history(&input, &number);
write_to_history(&input);
if process_line(input) {
return
}
@ -191,10 +191,21 @@ mod tests {
assert_eq!(mycmd, String::from("ls"));
}
//test add history line
#[test]
fn test_writehistline() {
inittests();
let towrite = String::from("pwd");
write_to_history(&towrite);
//Now check directly against the file
let filepath = dirs::home_dir().unwrap().join("history.rshell");
let file = File::open(filepath).expect("Error");
let mut reader = BufReader::new(file).lines();
let myline = String::from(reader.last().unwrap().expect("Error"));
let expected = String::from("2 pwd");
assert_eq!(myline.trim(), expected.trim());
}
}