Skip to content

Commit c2f1be0

Browse files
committedMar 23, 2025·
test(editor): add tests for offset_to_position (#9978)
Working on adding more comprehensive tests for the LSP code. This offset to position function is a core part of the range calculations, so we should start to have some tests for it.
1 parent 6c4b533 commit c2f1be0

File tree

1 file changed

+46
-0
lines changed
  • crates/oxc_language_server/src/linter

1 file changed

+46
-0
lines changed
 

‎crates/oxc_language_server/src/linter/mod.rs

+46
Original file line numberDiff line numberDiff line change
@@ -12,3 +12,49 @@ pub fn offset_to_position(offset: usize, source_text: &str) -> Position {
1212
let (line, column) = get_line_column(&rope, offset as u32, source_text);
1313
Position::new(line, column)
1414
}
15+
16+
#[cfg(test)]
17+
mod test {
18+
use crate::linter::offset_to_position;
19+
20+
#[test]
21+
fn single_line() {
22+
let source = "foo.bar!;";
23+
assert_position(source, 0, (0, 0));
24+
assert_position(source, 4, (0, 4));
25+
assert_position(source, 9, (0, 9));
26+
}
27+
28+
#[test]
29+
fn multi_line() {
30+
let source = "console.log(\n foo.bar!\n);";
31+
assert_position(source, 0, (0, 0));
32+
assert_position(source, 12, (0, 12));
33+
assert_position(source, 13, (1, 0));
34+
assert_position(source, 23, (1, 10));
35+
assert_position(source, 24, (2, 0));
36+
assert_position(source, 26, (2, 2));
37+
}
38+
39+
#[test]
40+
fn multi_byte() {
41+
let source = "let foo = \n '👍';";
42+
assert_position(source, 10, (0, 10));
43+
assert_position(source, 11, (1, 0));
44+
assert_position(source, 14, (1, 3));
45+
assert_position(source, 18, (1, 5));
46+
assert_position(source, 19, (1, 6));
47+
}
48+
49+
#[test]
50+
#[should_panic(expected = "out of bounds")]
51+
fn out_of_bounds() {
52+
offset_to_position(100, "foo");
53+
}
54+
55+
fn assert_position(source: &str, offset: usize, expected: (u32, u32)) {
56+
let position = offset_to_position(offset, source);
57+
assert_eq!(position.line, expected.0);
58+
assert_eq!(position.character, expected.1);
59+
}
60+
}

0 commit comments

Comments
 (0)
Please sign in to comment.