Dataset Viewer
Auto-converted to Parquet Duplicate
id
stringlengths
32
32
language
stringclasses
6 values
function_name
stringclasses
58 values
function_code
stringlengths
46
494
edge_case_type
stringlengths
3
26
edge_case_description
stringlengths
10
56
test_framework
stringclasses
5 values
unit_test
stringlengths
49
293
difficulty
stringclasses
3 values
8f5dff3040767b3d0e3be1c154c6ee82
python
find_max
def find_max(nums: list[int]) -> int: if not nums: raise ValueError("List must not be empty") return max(nums)
single_element
single-element list returns that element
pytest
def test_find_max_single(): assert find_max([42]) == 42
easy
1788eb26f588d778d8e55afa9ee47216
java
clamp
public static double clamp(double value, double lo, double hi) { return Math.max(lo, Math.min(hi, value)); }
within
value within range returned unchanged
junit4
@Test public void testClampWithin() { assertEquals(5.0, clamp(5, 0, 10), 1e-9); }
medium
addf121b5d1613a2d31fe7307621156f
go
FindMax
func FindMax(nums []int) (int, error) { if len(nums) == 0 { return 0, errors.New("empty slice") } max := nums[0] for _, v := range nums[1:] { if v > max { max = v } } return max, nil }
duplicates
duplicate max values return that max
testing
func TestFindMaxDuplicates(t *testing.T) { v, _ := FindMax([]int{5, 5, 3}) if v != 5 { t.Errorf("expected 5, got %v", v) } }
medium
3c212b51bd9ea9c67889bdd414e6fe68
javascript
uniqueBy
function uniqueBy(arr, key) { const seen = new Set(); return arr.filter(item => { const k = item[key]; if (seen.has(k)) return false; seen.add(k); return true; }); }
no_duplicates
no duplicate keys passes all through
jest
test("uniqueBy no dups", () => { const items = [{id:1},{id:2}]; expect(uniqueBy(items,"id").length).toBe(2); });
easy
7c231578d42808899d8933a0ffe97e27
rust
reverse_string
pub fn reverse_string(s: &str) -> String { s.chars().rev().collect() }
unicode
unicode chars reversed by char boundary
rust-test
#[test] fn test_reverse_unicode() { assert_eq!(reverse_string("héllo"), "olléh"); }
medium
6a2de3841755f519993049225dd35276
javascript
memoize
function memoize(fn) { const cache = new Map(); return (...args) => { const key = JSON.stringify(args); if (cache.has(key)) return cache.get(key); const result = fn(...args); cache.set(key, result); return result; }; }
zero_arg
zero-argument function is cached after first call
jest
test("memoize no args", () => { let calls = 0; const fn = memoize(() => { calls++; return 42; }); expect(fn()).toBe(42); expect(fn()).toBe(42); expect(calls).toBe(1); });
medium
4cbcb7a2bea1832d809934ef03a6ca55
typescript
parseJSON
export function parseJSON<T>(s: string): T | null { try { return JSON.parse(s) as T; } catch { return null; } }
null_literal
'null' string parses to null value
jest
test('parseJSON null literal', () => { expect(parseJSON('null')).toBeNull(); });
medium
8612040f0ee4f49f60b57ed3b7f48922
typescript
chunk
export function chunk<T>(arr: T[], size: number): T[][] { if (size <= 0) throw new Error('size must be positive'); const result: T[][] = []; for (let i = 0; i < arr.length; i += size) result.push(arr.slice(i, i + size)); return result; }
size_zero
size 0 throws
jest
test('chunk zero size', () => { expect(() => chunk([1,2,3], 0)).toThrow(); });
medium
0fb557da8453317d8d032f507c7e1c2a
typescript
chunk
export function chunk<T>(arr: T[], size: number): T[][] { if (size <= 0) throw new Error('size must be positive'); const result: T[][] = []; for (let i = 0; i < arr.length; i += size) result.push(arr.slice(i, i + size)); return result; }
remainder
uneven length last chunk is smaller
jest
test('chunk remainder', () => { expect(chunk([1,2,3,4,5],2)).toEqual([[1,2],[3,4],[5]]); });
medium
180ccdd8db9c2ebe7bf7889adc9c3257
python
gcd
def gcd(a: int, b: int) -> int: while b: a, b = b, a % b return a
coprime
gcd of coprime numbers is 1
pytest
def test_gcd_coprime(): assert gcd(13, 7) == 1
medium
85c8bda3653f84986142ed4b13db50e4
python
celsius_to_fahrenheit
def celsius_to_fahrenheit(c: float) -> float: return c * 9 / 5 + 32
negative_celsius
negative Celsius converts to correct Fahrenheit
pytest
def test_celsius_negative(): assert celsius_to_fahrenheit(-40) == -40.0
medium
aea7c5e5132313af8e26894fea3d1588
python
chunk_list
def chunk_list(lst: list, size: int) -> list[list]: if size <= 0: raise ValueError("size must be positive") return [lst[i:i + size] for i in range(0, len(lst), size)]
exact_multiple
list length is exact multiple of chunk size
pytest
def test_chunk_exact(): assert chunk_list([1, 2, 3, 4], 2) == [[1, 2], [3, 4]]
easy
3d71fbca6d366aa728075274984f1ce4
python
fizzbuzz
def fizzbuzz(n: int) -> str: if n % 15 == 0: return "FizzBuzz" if n % 3 == 0: return "Fizz" if n % 5 == 0: return "Buzz" return str(n)
not_divisible
number not divisible by 3 or 5 returns string of n
pytest
def test_fizzbuzz_plain(): assert fizzbuzz(7) == "7"
medium
a32ed98cf96d9012c648921a362084d9
python
factorial
def factorial(n: int) -> int: if n < 0: raise ValueError("n must be non-negative") if n == 0: return 1 return n * factorial(n - 1)
one_input
factorial of 1 is 1
pytest
def test_factorial_one(): assert factorial(1) == 1
easy
ffb235335b0ef809c4cec992ef39596d
java
factorial
public static long factorial(int n) { if (n < 0) throw new IllegalArgumentException("n must be non-negative"); long result = 1; for (int i = 2; i <= n; i++) result *= i; return result; }
zero
factorial(0) is 1
junit4
@Test public void testFactorialZero() { assertEquals(1L, factorial(0)); }
easy
457bd0bd1bb017bb43babf394df00a5c
python
cumulative_sum
def cumulative_sum(nums: list[int]) -> list[int]: """Return running cumulative sum of nums.""" result, total = [], 0 for n in nums: total += n result.append(total) return result
empty_list
empty list returns empty list
pytest
def test_cumsum_empty(): assert cumulative_sum([]) == []
easy
aabab1f1c05a1017d430f38f2f5f78e3
java
wordCount
public static Map<String, Integer> wordCount(String text) { Map<String, Integer> counts = new HashMap<>(); if (text == null || text.isBlank()) return counts; for (String word : text.toLowerCase().split("\\s+")) { counts.merge(word, 1, Integer::sum); } return counts; }
null_input
null input returns empty map
junit4
@Test public void testWordCountNull() { assertTrue(wordCount(null).isEmpty()); }
medium
c7470fa12d5ba01e87a7f9c8c40bd95c
java
findMax
public static int findMax(int[] arr) { if (arr.length == 0) throw new IllegalArgumentException("Array is empty"); int max = arr[0]; for (int v : arr) if (v > max) max = v; return max; }
duplicates
max value appears multiple times
junit4
@Test public void testFindMaxDuplicates() { assertEquals(5, findMax(new int[]{5, 5, 3})); }
medium
8f08b93f7068fd80a6c96537f9da42aa
java
reverseString
public static String reverseString(String s) { return new StringBuilder(s).reverse().toString(); }
palindrome
palindrome returns itself
junit4
@Test public void testReversePalindrome() { assertEquals("racecar", reverseString("racecar")); }
easy
6ed22e9d050c298707a04e77acccf275
typescript
pick
export function pick<T extends object, K extends keyof T>(obj: T, keys: K[]): Pick<T, K> { const result = {} as Pick<T, K>; for (const k of keys) { if (k in obj) result[k] = obj[k]; } return result; }
all_keys
picking all keys returns equivalent object
jest
test('pick all keys', () => { expect(pick({a:1,b:2}, ['a','b'])).toEqual({a:1,b:2}); });
easy
1557f66d45ec09226cc6cc9593be7a2b
rust
divide
pub fn divide(a: f64, b: f64) -> Result<f64, String> { if b == 0.0 { return Err("Division by zero".to_string()); } Ok(a / b) }
both_negative
both negative yields positive
rust-test
#[test] fn test_divide_both_neg() { assert_eq!(divide(-6.0, -3.0).unwrap(), 2.0); }
medium
c798c3654d6c54b0d71a4cafefe1a856
typescript
deepEqual
export function deepEqual(a: unknown, b: unknown): boolean { return JSON.stringify(a) === JSON.stringify(b); }
array_order
array order matters for equality
jest
test('deepEqual array order', () => { expect(deepEqual([1,2], [2,1])).toBe(false); });
medium
13ba608609022f7d7a6cf3d44b170c28
rust
clamp
pub fn clamp(value: f64, lo: f64, hi: f64) -> f64 { if value < lo { lo } else if value > hi { hi } else { value } }
within
value within range unchanged
rust-test
#[test] fn test_clamp_within() { assert_eq!(clamp(5.0, 0.0, 10.0), 5.0); }
medium
cae23a2c6b4b1d23604ef44e5917d13e
javascript
divide
function divide(a, b) { if (b === 0) throw new Error('Division by zero'); return a / b; }
negative_inputs
negative numerator and positive divisor
jest
test("divide negative numerator", () => { expect(divide(-10, 2)).toBe(-5); });
medium
2e1b377a50fb8f018e87aad02e4883c4
python
truncate
def truncate(s: str, max_len: int) -> str: if len(s) <= max_len: return s return s[:max_len] + "..."
empty_string
empty string is returned unchanged
pytest
def test_truncate_empty(): assert truncate("", 5) == ""
easy
d7fdafdec0c62c7e899b81deeac2db3b
java
divide
public static double divide(double a, double b) { if (b == 0) throw new ArithmeticException("Division by zero"); return a / b; }
both_negative
both negative operands yield positive
junit4
@Test public void testDivideBothNegative() { assertEquals(2.0, divide(-6, -3), 1e-9); }
medium
45895352d09abbbb9c9cb89a6098023b
rust
divide
pub fn divide(a: f64, b: f64) -> Result<f64, String> { if b == 0.0 { return Err("Division by zero".to_string()); } Ok(a / b) }
zero_numerator
a=0 returns Ok(0)
rust-test
#[test] fn test_divide_zero_num() { assert_eq!(divide(0.0, 5.0).unwrap(), 0.0); }
medium
ea37442ebc50663de3c50c29671be0cc
python
is_palindrome
def is_palindrome(s: str) -> bool: s = s.lower().replace(" ", "") return s == s[::-1]
numeric_palindrome
numeric palindrome string is correctly identified
pytest
def test_is_palindrome_numeric(): assert is_palindrome("12321") is True
medium
3f854021ffd8b18e508a4c93a8ea014b
go
FindMax
func FindMax(nums []int) (int, error) { if len(nums) == 0 { return 0, errors.New("empty slice") } max := nums[0] for _, v := range nums[1:] { if v > max { max = v } } return max, nil }
empty_slice
empty slice returns error
testing
func TestFindMaxEmpty(t *testing.T) { _, err := FindMax([]int{}) if err == nil { t.Error("expected error for empty slice") } }
easy
92065080d78afa9978d9888abe5eaa48
typescript
groupBy
export function groupBy<T>(arr: T[], key: keyof T): Record<string, T[]> { return arr.reduce((acc, item) => { const k = String(item[key]); if (!acc[k]) acc[k] = []; acc[k].push(item); return acc; }, {} as Record<string, T[]>); }
preserves_order
within each group order is preserved
jest
test('groupBy order', () => { const items = [{k:'a',i:1},{k:'b',i:2},{k:'a',i:3}]; expect(groupBy(items,'k').a.map(x=>x.i)).toEqual([1,3]); });
medium
4f3d1c32d94185a8bcc0ccdb521270cb
python
is_palindrome
def is_palindrome(s: str) -> bool: s = s.lower().replace(" ", "") return s == s[::-1]
case_insensitive
palindrome check is case-insensitive
pytest
def test_is_palindrome_case(): assert is_palindrome("Racecar") is True
medium
a5a73e0d676dc91cd23561b3ec5fb7c9
javascript
memoize
function memoize(fn) { const cache = new Map(); return (...args) => { const key = JSON.stringify(args); if (cache.has(key)) return cache.get(key); const result = fn(...args); cache.set(key, result); return result; }; }
caches_result
memoized function returns cached result on second call
jest
test("memoize caches", () => { let calls = 0; const fn = memoize((x) => { calls++; return x * 2; }); fn(5); fn(5); expect(calls).toBe(1); });
medium
52adbc9993afacd03336a571e102e5a5
python
Stack
class Stack: def __init__(self): self._data = [] def push(self, item): self._data.append(item) def pop(self): if not self._data: raise IndexError("pop from empty stack") return self._data.pop() def peek(self): if not self._data: raise In...
push_duplicate_values
duplicate values are stored and returned in order
pytest
def test_stack_duplicates(): s = Stack() s.push(7) s.push(7) assert s.pop() == 7 assert s.pop() == 7 assert s.is_empty()
medium
8933f14b14463cd2a7fb394f56f7af71
python
find_max
def find_max(nums: list[int]) -> int: if not nums: raise ValueError("List must not be empty") return max(nums)
already_sorted
sorted list returns last element
pytest
def test_find_max_sorted(): assert find_max([1, 2, 3, 4, 5]) == 5
medium
8bd86f08f9fa5114c31cf1eef8bc27ae
python
Stack
class Stack: def __init__(self): self._data = [] def push(self, item): self._data.append(item) def pop(self): if not self._data: raise IndexError("pop from empty stack") return self._data.pop() def peek(self): if not self._data: raise In...
peek_empty
peeking empty stack raises IndexError
pytest
import pytest def test_stack_peek_empty(): s = Stack() with pytest.raises(IndexError): s.peek()
medium
7fdb430746cc2e3f688f219fd87e71db
javascript
clamp
function clamp(value, lo, hi) { return Math.max(lo, Math.min(hi, value)); }
above_hi
value above hi returns hi
jest
test("clamp above hi", () => { expect(clamp(15, 0, 10)).toBe(10); });
easy
bcaed74b65864ccdae525bda7e7aacb2
python
levenshtein
def levenshtein(s: str, t: str) -> int: """Compute Levenshtein (edit) distance between s and t.""" m, n = len(s), len(t) dp = list(range(n + 1)) for i in range(1, m + 1): prev = dp[0] dp[0] = i for j in range(1, n + 1): tmp = dp[j] if s[i-1] == t[j-1]: ...
completely_different
entirely different strings of equal length
pytest
def test_lev_different(): assert levenshtein("abc", "xyz") == 3
medium
472da75d55caa8c6c550bdb47556a461
python
truncate
def truncate(s: str, max_len: int) -> str: if len(s) <= max_len: return s return s[:max_len] + "..."
max_len_zero
max_len of 0 returns only ellipsis
pytest
def test_truncate_zero_max(): assert truncate("hello", 0) == "..."
medium
116028ac4edfc0529916ac5fe8f57876
javascript
countOccurrences
function countOccurrences(arr, val) { return arr.filter(x => x === val).length; }
empty_array
empty array returns 0
jest
test("countOccurrences empty", () => { expect(countOccurrences([], 5)).toBe(0); });
easy
58685c535f2198b6b0339ba74e8fdcfb
javascript
debounce
function debounce(fn, delay) { let timer; return (...args) => { clearTimeout(timer); timer = setTimeout(() => fn(...args), delay); }; }
fires_after_delay
debounced function fires once after delay
jest
test("debounce fires after delay", async () => { jest.useFakeTimers(); const fn = jest.fn(); const debounced = debounce(fn, 100); debounced(); debounced(); jest.runAllTimers(); expect(fn).toHaveBeenCalledTimes(1); jest.useRealTimers(); });
hard
04ca7dcaa2d4532e1369973f9a222455
typescript
flattenDeep
export function flattenDeep(arr: unknown[]): unknown[] { const result: unknown[] = []; const stack = [...arr]; while (stack.length) { const item = stack.pop(); if (Array.isArray(item)) { stack.push(...item); } else { result.unshift(item); } } return result; }
already_flat
already flat array returned unchanged
jest
test('flattenDeep flat', () => { expect(flattenDeep([1,2,3])).toEqual([1,2,3]); });
easy
064cc6e5a5371de7ec1417a2dd8f83be
python
merge_sorted
def merge_sorted(a: list[int], b: list[int]) -> list[int]: """Merge two sorted lists into one sorted list.""" result, i, j = [], 0, 0 while i < len(a) and j < len(b): if a[i] <= b[j]: result.append(a[i]); i += 1 else: result.append(b[j]); j += 1 result.extend(a[i:...
unequal_lengths
one list much longer than the other
pytest
def test_merge_unequal(): assert merge_sorted([1, 2, 3, 4, 5], [3]) == [1, 2, 3, 3, 4, 5]
medium
82aff88f7640f56a1e2e29f9101eb653
java
divide
public static double divide(double a, double b) { if (b == 0) throw new ArithmeticException("Division by zero"); return a / b; }
negative_numerator
negative numerator returns correct result
junit4
@Test public void testDivideNegative() { assertEquals(-5.0, divide(-10, 2), 1e-9); }
medium
4f452843be4f55e4e90a472eb4559f81
python
Stack
class Stack: def __init__(self): self._data = [] def push(self, item): self._data.append(item) def pop(self): if not self._data: raise IndexError("pop from empty stack") return self._data.pop() def peek(self): if not self._data: raise In...
lifo_order
stack returns items in LIFO order
pytest
def test_stack_lifo(): s = Stack() for v in [1, 2, 3]: s.push(v) assert s.pop() == 3 assert s.pop() == 2 assert s.pop() == 1
easy
7e27c43a012f026455db47b06855482b
javascript
debounce
function debounce(fn, delay) { let timer; return (...args) => { clearTimeout(timer); timer = setTimeout(() => fn(...args), delay); }; }
resets_timer
rapid calls reset the timer and fire only once
jest
test("debounce resets timer", async () => { jest.useFakeTimers(); const fn = jest.fn(); const debounced = debounce(fn, 200); debounced(); jest.advanceTimersByTime(100); debounced(); jest.advanceTimersByTime(200); expect(fn).toHaveBeenCalledTimes(1); jest.useRealTimers(); });
hard
f9ad51afefc4c39ca724895c0edfaf9b
go
Fibonacci
func Fibonacci(n int) (int, error) { if n < 0 { return 0, errors.New("n must be non-negative") } if n <= 1 { return n, nil } a, b := 0, 1 for i := 2; i <= n; i++ { a, b = b, a+b } return b, nil }
two
Fibonacci(2) is 1
testing
func TestFibTwo(t *testing.T) { v, _ := Fibonacci(2) if v != 1 { t.Errorf("expected 1, got %d", v) } }
easy
beee9e831285dc2e1b412c6bca93d200
rust
find_max
pub fn find_max(nums: &[i64]) -> Option<i64> { nums.iter().copied().reduce(i64::max) }
empty_slice
empty slice returns None
rust-test
#[test] fn test_find_max_empty() { assert_eq!(find_max(&[]), None); }
easy
22b35ff787ab64456232ad8ae5dc4b95
python
factorial
def factorial(n: int) -> int: if n < 0: raise ValueError("n must be non-negative") if n == 0: return 1 return n * factorial(n - 1)
two_input
factorial of 2 is 2
pytest
def test_factorial_two(): assert factorial(2) == 2
medium
0c68ef8c2ed2328856e2c8e239dc61c8
javascript
pipe
function pipe(...fns) { return (x) => fns.reduce((v, f) => f(v), x); }
order_matters
order of functions in pipe matters
jest
test("pipe order matters", () => { const ab = pipe(x => x + 1, x => x * 2); const ba = pipe(x => x * 2, x => x + 1); expect(ab(3)).not.toBe(ba(3)); });
hard
84be0570bdd07e412bcda11ebce6596a
python
string_to_int
def string_to_int(s: str) -> int | None: """Parse s as integer, returning None on failure.""" try: return int(s.strip()) except (ValueError, AttributeError): return None
mixed_alpha_num
mixed alphanumeric string returns None
pytest
def test_str2int_mixed(): assert string_to_int('12abc') is None
medium
f0f4800a0f7c9b5bee70041c8825a4e6
javascript
reverseString
function reverseString(s) { return s.split('').reverse().join(''); }
empty_string
reversing empty string returns empty string
jest
test("reverseString empty", () => { expect(reverseString("")).toBe(""); });
easy
c9fd8ea6c914d41a90e84f393b7b89ab
javascript
chunk
function chunk(arr, size) { if (size <= 0) throw new Error('size must be positive'); const result = []; for (let i = 0; i < arr.length; i += size) { result.push(arr.slice(i, i + size)); } return result; }
size_zero
chunk size of 0 throws
jest
test("chunk size zero throws", () => { expect(() => chunk([1, 2], 0)).toThrow(); });
medium
dbfd5048f576d86924bad7da80b05051
javascript
isPalindrome
function isPalindrome(s) { const clean = s.toLowerCase().replace(/\s/g, ''); return clean === clean.split('').reverse().join(''); }
case_insensitive
case-insensitive check
jest
test("isPalindrome case insensitive", () => { expect(isPalindrome("Racecar")).toBe(true); });
medium
5be4052ac3cb712a6d4ea8225900dbc0
python
find_max
def find_max(nums: list[int]) -> int: if not nums: raise ValueError("List must not be empty") return max(nums)
duplicates
list with duplicate max values returns that max
pytest
def test_find_max_duplicates(): assert find_max([5, 5, 3, 5]) == 5
medium
74100c03270700dba3ec693e050f6b6d
java
reverseString
public static String reverseString(String s) { return new StringBuilder(s).reverse().toString(); }
normal_word
normal word reversed correctly
junit4
@Test public void testReverseWord() { assertEquals("olleh", reverseString("hello")); }
medium
62f0305c30c4c5e972e4a69702a02254
typescript
omit
export function omit<T extends object, K extends keyof T>(obj: T, keys: K[]): Omit<T, K> { const result = { ...obj }; for (const k of keys) delete result[k]; return result as Omit<T, K>; }
nonexistent_key
omitting key not in object returns unchanged copy
jest
test('omit nonexistent', () => { const result = omit({a:1} as any, ['z' as any]); expect(result).toEqual({a:1}); });
medium
057bc92ea08d2f9d23ff25d42c704d72
python
moving_average
def moving_average(data: list[float], window: int) -> list[float]: if window <= 0: raise ValueError("window must be positive") return [sum(data[i:i+window]) / window for i in range(len(data) - window + 1)]
window_larger_than_data
window larger than data length returns empty list
pytest
def test_moving_avg_window_too_large(): assert moving_average([1.0, 2.0], 5) == []
medium
a50357228f693b6255d731d5bce70697
python
string_to_int
def string_to_int(s: str) -> int | None: """Parse s as integer, returning None on failure.""" try: return int(s.strip()) except (ValueError, AttributeError): return None
none_input
None input returns None without raising
pytest
def test_str2int_none(): assert string_to_int(None) is None
medium
98bf02cea9538d5f25aa06b57228b630
java
clamp
public static double clamp(double value, double lo, double hi) { return Math.max(lo, Math.min(hi, value)); }
above
value above hi returns hi
junit4
@Test public void testClampAbove() { assertEquals(10.0, clamp(15, 0, 10), 1e-9); }
medium
6fd199fa4bcb05bd37ccc212f5761be6
python
divide
def divide(a: float, b: float) -> float: """Return a divided by b.""" return a / b
float_precision
floating point inputs return correct quotient
pytest
def test_divide_float_precision(): result = divide(1.0, 3.0) assert abs(result - 0.3333333333333333) < 1e-10
medium
59eeff85e6a15ffc8a3428275cad86f3
java
factorial
public static long factorial(int n) { if (n < 0) throw new IllegalArgumentException("n must be non-negative"); long result = 1; for (int i = 2; i <= n; i++) result *= i; return result; }
ten
factorial(10) is 3628800
junit4
@Test public void testFactorialTen() { assertEquals(3628800L, factorial(10)); }
medium
8e8165aa8e985d07ec0383963f13b94f
typescript
deepEqual
export function deepEqual(a: unknown, b: unknown): boolean { return JSON.stringify(a) === JSON.stringify(b); }
null_vs_undefined
null and undefined are not deeply equal
jest
test('deepEqual null vs undefined', () => { expect(deepEqual(null, undefined)).toBe(false); });
hard
ce36cd4b56e146d8e9544670db8395ce
python
deep_get
def deep_get(d: dict, *keys, default=None): for key in keys: if not isinstance(d, dict): return default d = d.get(key, default) return d
missing_key
missing key returns default
pytest
def test_deep_get_missing(): assert deep_get({"a": 1}, "b") is None
medium
1df270ba04b215bd06a39fc68bb3aa2f
python
levenshtein
def levenshtein(s: str, t: str) -> int: """Compute Levenshtein (edit) distance between s and t.""" m, n = len(s), len(t) dp = list(range(n + 1)) for i in range(1, m + 1): prev = dp[0] dp[0] = i for j in range(1, n + 1): tmp = dp[j] if s[i-1] == t[j-1]: ...
single_substitution
one character substitution has distance 1
pytest
def test_lev_sub(): assert levenshtein("cat", "bat") == 1
medium
7db93dfdf319adc840c65449e5c2d11b
python
count_vowels
def count_vowels(s: str) -> int: return sum(1 for c in s.lower() if c in "aeiou")
numbers_punctuation
digits and punctuation are not counted as vowels
pytest
def test_count_vowels_digits(): assert count_vowels("h3ll0!") == 0
medium
c791a38e27f3c4b26d4d2d54bee262f7
rust
clamp
pub fn clamp(value: f64, lo: f64, hi: f64) -> f64 { if value < lo { lo } else if value > hi { hi } else { value } }
at_lo
value at lo returns lo
rust-test
#[test] fn test_clamp_at_lo() { assert_eq!(clamp(0.0, 0.0, 10.0), 0.0); }
easy
829f30edd436f25373ace690a2f1fa43
javascript
uniqueBy
function uniqueBy(arr, key) { const seen = new Set(); return arr.filter(item => { const k = item[key]; if (seen.has(k)) return false; seen.add(k); return true; }); }
empty_array
empty array returns empty
jest
test("uniqueBy empty", () => { expect(uniqueBy([], "id")).toEqual([]); });
easy
2a511df340f0c2d8765640bec66fc5b1
rust
fibonacci
pub fn fibonacci(n: u64) -> u64 { if n <= 1 { return n; } let (mut a, mut b) = (0u64, 1u64); for _ in 2..=n { let c = a + b; a = b; b = c; } b }
one
fibonacci(1) is 1
rust-test
#[test] fn test_fib_one() { assert_eq!(fibonacci(1), 1); }
easy
6bfefb85c752c9b08756725952d03e9f
python
Stack
class Stack: def __init__(self): self._data = [] def push(self, item): self._data.append(item) def pop(self): if not self._data: raise IndexError("pop from empty stack") return self._data.pop() def peek(self): if not self._data: raise In...
is_empty_after_push
stack is not empty after push
pytest
def test_stack_not_empty_after_push(): s = Stack() s.push(1) assert s.is_empty() is False
easy
f59e9a180e14d8ef9988da82b8a1039e
python
fizzbuzz
def fizzbuzz(n: int) -> str: if n % 15 == 0: return "FizzBuzz" if n % 3 == 0: return "Fizz" if n % 5 == 0: return "Buzz" return str(n)
divisible_by_5
multiple of 5 returns 'Buzz'
pytest
def test_fizzbuzz_buzz(): assert fizzbuzz(10) == "Buzz"
medium
521b204d3ae8b9eabda42732616c4aef
python
chunk_list
def chunk_list(lst: list, size: int) -> list[list]: if size <= 0: raise ValueError("size must be positive") return [lst[i:i + size] for i in range(0, len(lst), size)]
size_zero
chunk size of 0 raises ValueError
pytest
import pytest def test_chunk_size_zero(): with pytest.raises(ValueError): chunk_list([1, 2, 3], 0)
medium
ee86829ff5e534cab3b4511ce015ac69
rust
is_prime
pub fn is_prime(n: u64) -> bool { if n < 2 { return false; } if n == 2 { return true; } if n % 2 == 0 { return false; } let mut i = 3u64; while i * i <= n { if n % i == 0 { return false; } i += 2; } true }
zero
0 is not prime
rust-test
#[test] fn test_prime_zero() { assert!(!is_prime(0)); }
easy
9fce1f2e67d05d4901660137cf748fd2
python
moving_average
def moving_average(data: list[float], window: int) -> list[float]: if window <= 0: raise ValueError("window must be positive") return [sum(data[i:i+window]) / window for i in range(len(data) - window + 1)]
window_negative
negative window raises ValueError
pytest
import pytest def test_moving_avg_negative_window(): with pytest.raises(ValueError): moving_average([1.0, 2.0], -1)
medium
811d9ec584cdfef63495c82e17ec9635
python
divide
def divide(a: float, b: float) -> float: """Return a divided by b.""" return a / b
zero_numerator
zero divided by any nonzero number is zero
pytest
def test_divide_zero_numerator(): assert divide(0, 5) == 0.0
medium
f33153eced572d8813d58a3403039cbf
rust
is_prime
pub fn is_prime(n: u64) -> bool { if n < 2 { return false; } if n == 2 { return true; } if n % 2 == 0 { return false; } let mut i = 3u64; while i * i <= n { if n % i == 0 { return false; } i += 2; } true }
two
2 is prime
rust-test
#[test] fn test_prime_two() { assert!(is_prime(2)); }
medium
19e7bcbc7b925db29583f111af8563e9
typescript
parseJSON
export function parseJSON<T>(s: string): T | null { try { return JSON.parse(s) as T; } catch { return null; } }
valid_array
valid JSON array is parsed
jest
test('parseJSON valid array', () => { expect(parseJSON<number[]>('[1,2,3]')).toEqual([1,2,3]); });
easy
66572fc65047a6aa6a86641614e6c133
java
findMax
public static int findMax(int[] arr) { if (arr.length == 0) throw new IllegalArgumentException("Array is empty"); int max = arr[0]; for (int v : arr) if (v > max) max = v; return max; }
single_element
single element returns that element
junit4
@Test public void testFindMaxSingle() { assertEquals(42, findMax(new int[]{42})); }
easy
f9a17f44956d3b9d9b859022ffcdda44
javascript
pipe
function pipe(...fns) { return (x) => fns.reduce((v, f) => f(v), x); }
empty_pipeline
empty pipe returns identity
jest
test("pipe empty", () => { const id = pipe(); expect(id(5)).toBe(5); });
medium
84ee4d197ab08c809f998c53f212adb5
javascript
chunk
function chunk(arr, size) { if (size <= 0) throw new Error('size must be positive'); const result = []; for (let i = 0; i < arr.length; i += size) { result.push(arr.slice(i, i + size)); } return result; }
exact_multiple
exact multiple length splits evenly
jest
test("chunk exact multiple", () => { expect(chunk([1, 2, 3, 4], 2)).toEqual([[1, 2], [3, 4]]); });
easy
922c121d72d4ed5bfbccf336614bd632
go
ReverseString
func ReverseString(s string) string { runes := []rune(s) for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 { runes[i], runes[j] = runes[j], runes[i] } return string(runes) }
empty
empty string returns empty
testing
func TestReverseEmpty(t *testing.T) { if got := ReverseString(""); got != "" { t.Errorf("expected "", got %q", got) } }
easy
54a97350c385cf42290e993332c30b71
go
Clamp
func Clamp(value, lo, hi float64) float64 { if value < lo { return lo } if value > hi { return hi } return value }
below_lo
value below lo returns lo
testing
func TestClampBelow(t *testing.T) { if got := Clamp(-5, 0, 10); got != 0 { t.Errorf("expected 0, got %v", got) } }
easy
8179129e8620dcc3835bb3bb33d73fec
python
is_prime
def is_prime(n: int) -> bool: if n < 2: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True
negative
negative numbers are not prime
pytest
def test_is_prime_negative(): assert is_prime(-7) is False
medium
7fd3f7142e6c05e0953d0207f1cade69
javascript
deepClone
function deepClone(obj) { return JSON.parse(JSON.stringify(obj)); }
primitive
cloning a primitive number returns same value
jest
test("deepClone primitive", () => { expect(deepClone(42)).toBe(42); });
medium
28d363213762920384c8f131479ac3e5
python
clamp
def clamp(value: float, lo: float, hi: float) -> float: return max(lo, min(hi, value))
lo_equals_hi
when lo equals hi, any value returns that bound
pytest
def test_clamp_lo_eq_hi(): assert clamp(5, 3, 3) == 3
medium
4dc390e3270fed55734dca7c655817a4
javascript
findMax
function findMax(arr) { if (arr.length === 0) throw new Error('Array is empty'); return Math.max(...arr); }
duplicates
array with duplicates of max returns max
jest
test("findMax duplicates", () => { expect(findMax([3, 3, 1])).toBe(3); });
medium
79a947226bdeb15336b72fb46bb2c33a
python
zip_with
def zip_with(fn, a: list, b: list) -> list: """Apply fn element-wise to paired elements of a and b.""" return [fn(x, y) for x, y in zip(a, b)]
single_element
single element lists return single element
pytest
def test_zip_with_single(): assert zip_with(max, [3], [5]) == [5]
easy
cbf7c0df91d42e482b01da2bcd2495a7
python
chunk_list
def chunk_list(lst: list, size: int) -> list[list]: if size <= 0: raise ValueError("size must be positive") return [lst[i:i + size] for i in range(0, len(lst), size)]
size_larger_than_list
chunk size larger than list returns one chunk
pytest
def test_chunk_size_larger(): assert chunk_list([1, 2], 10) == [[1, 2]]
easy
f8f2d58db9f87c6b00124ebae0cc93b6
typescript
omit
export function omit<T extends object, K extends keyof T>(obj: T, keys: K[]): Omit<T, K> { const result = { ...obj }; for (const k of keys) delete result[k]; return result as Omit<T, K>; }
all_keys
omitting all keys returns empty object
jest
test('omit all keys', () => { expect(omit({a:1,b:2}, ['a','b'])).toEqual({}); });
medium
b38b6524071ad36e6636bd243c72c34f
rust
fibonacci
pub fn fibonacci(n: u64) -> u64 { if n <= 1 { return n; } let (mut a, mut b) = (0u64, 1u64); for _ in 2..=n { let c = a + b; a = b; b = c; } b }
zero
fibonacci(0) is 0
rust-test
#[test] fn test_fib_zero() { assert_eq!(fibonacci(0), 0); }
easy
a9a67db15023c73d8f058f9d1514658b
javascript
findMax
function findMax(arr) { if (arr.length === 0) throw new Error('Array is empty'); return Math.max(...arr); }
single_element
single element array returns that element
jest
test("findMax single element", () => { expect(findMax([42])).toBe(42); });
easy
9111917b13e869bca8630febc206b5d2
typescript
chunk
export function chunk<T>(arr: T[], size: number): T[][] { if (size <= 0) throw new Error('size must be positive'); const result: T[][] = []; for (let i = 0; i < arr.length; i += size) result.push(arr.slice(i, i + size)); return result; }
empty_array
empty array returns empty
jest
test('chunk empty', () => { expect(chunk([], 3)).toEqual([]); });
easy
db11f4bb1246b5bb787f63000e6f9e1e
go
Unique
func Unique(nums []int) []int { seen := make(map[int]bool) result := []int{} for _, v := range nums { if !seen[v] { seen[v] = true result = append(result, v) } } return result }
empty_slice
empty slice returns empty
testing
func TestUniqueEmpty(t *testing.T) { result := Unique([]int{}) if len(result) != 0 { t.Errorf("expected empty, got %v", result) } }
easy
6544b0f0c1d605611fc063531287426f
java
factorial
public static long factorial(int n) { if (n < 0) throw new IllegalArgumentException("n must be non-negative"); long result = 1; for (int i = 2; i <= n; i++) result *= i; return result; }
one
factorial(1) is 1
junit4
@Test public void testFactorialOne() { assertEquals(1L, factorial(1)); }
easy
c6171c53b84253d1e03389c679181b46
python
factorial
def factorial(n: int) -> int: if n < 0: raise ValueError("n must be non-negative") if n == 0: return 1 return n * factorial(n - 1)
negative_input
negative input raises ValueError
pytest
import pytest def test_factorial_negative(): with pytest.raises(ValueError): factorial(-1)
medium
788dfb9811f1ccf99dcaaaa2a4ce6cfe
rust
find_max
pub fn find_max(nums: &[i64]) -> Option<i64> { nums.iter().copied().reduce(i64::max) }
all_negative
all negative returns least negative
rust-test
#[test] fn test_find_max_neg() { assert_eq!(find_max(&[-3, -1, -7]), Some(-1)); }
medium
7c38372669cab1258c155379a317351d
python
divide
def divide(a: float, b: float) -> float: """Return a divided by b.""" return a / b
negative_numerator
negative numerator returns correct negative result
pytest
def test_divide_negative_numerator(): assert divide(-10, 2) == -5.0
medium
7d2db485c51743d3ad14425af0bebeaf
python
reverse_string
def reverse_string(s: str) -> str: return s[::-1]
whitespace
whitespace characters are preserved in reverse
pytest
def test_reverse_whitespace(): assert reverse_string("a b") == "b a"
medium
f9b9362622345f254d8045ceb46f7b24
javascript
pipe
function pipe(...fns) { return (x) => fns.reduce((v, f) => f(v), x); }
single_fn
pipe with single function applies it
jest
test("pipe single fn", () => { const double = pipe(x => x * 2); expect(double(3)).toBe(6); });
easy
ccc73a8e1758e796d4a388ae656eb38b
rust
count_vowels
pub fn count_vowels(s: &str) -> usize { s.chars().filter(|c| "aeiouAEIOU".contains(*c)).count() }
uppercase
uppercase vowels counted
rust-test
#[test] fn test_vowels_upper() { assert_eq!(count_vowels("AEIOU"), 5); }
medium
465643b4c162f98272969caa5fac2e06
python
zip_with
def zip_with(fn, a: list, b: list) -> list: """Apply fn element-wise to paired elements of a and b.""" return [fn(x, y) for x, y in zip(a, b)]
string_fn
string concatenation function applied element-wise
pytest
def test_zip_with_strings(): result = zip_with(lambda x, y: x + y, ['a', 'b'], ['1', '2']) assert result == ['a1', 'b2']
medium
End of preview. Expand in Data Studio

unit-test-edge-cases

A synthetic dataset of 380 curated (function, edge-case, unit-test) triples across 6 programming languages. Designed to train and evaluate code models on their ability to generate comprehensive unit tests targeting boundary conditions and edge cases.

Dataset Summary

Split Examples
train 304
validation 38
test 38
Total 380

Languages & Frameworks

Language Framework Examples
Python pytest 169
JavaScript jest 57
TypeScript jest 39
Go testing 42
Java JUnit 4 36
Rust rust-test 37

Schema

Each example is a JSON object with these fields:

Field Type Description
id string MD5 of `lang
language string python, javascript, typescript, go, java, rust
function_name string Name of the function under test
function_code string Complete function implementation
edge_case_type string Slug identifying the edge case category
edge_case_description string Human-readable description of what is tested
test_framework string pytest, jest, testing, junit4, rust-test
unit_test string Complete, runnable unit test
difficulty string easy, medium, or hard

Edge Case Categories

The dataset covers these edge case patterns:

  • Boundary values: empty collections, single elements, exact boundary values
  • Zero/null handling: zero divisors, empty strings, None/null inputs
  • Negative numbers: negative inputs where positive expected
  • Type coercion: strict vs. loose equality, type mismatch
  • Duplicate values: lists with repeated elements
  • Case sensitivity: case-insensitive vs. case-sensitive behavior
  • Unicode: multi-byte and non-ASCII character handling
  • Large/overflow: very large numbers, long inputs
  • Error conditions: expected exceptions and error returns
  • Commutativity/symmetry: order invariance properties

Difficulty Distribution

Difficulty Count
easy 153
medium 207
hard 20

Sample Example

{
  "id": "a1b2c3...",
  "language": "python",
  "function_name": "factorial",
  "function_code": "def factorial(n: int) -> int:\n    if n < 0:\n        raise ValueError(\"n must be non-negative\")\n    if n == 0:\n        return 1\n    return n * factorial(n - 1)",
  "edge_case_type": "negative_input",
  "edge_case_description": "negative input raises ValueError",
  "test_framework": "pytest",
  "unit_test": "import pytest\n\ndef test_factorial_negative():\n    with pytest.raises(ValueError):\n        factorial(-1)",
  "difficulty": "medium"
}

Generation Methodology

  1. Hand-crafted functions: 40+ functions across 6 languages covering common patterns (arithmetic, string manipulation, collections, data structures, algorithms).
  2. Parametric edge case templates: Each function has 4–10 hand-authored edge case tests targeting known failure modes.
  3. Deduplication: MD5 on lang|function_name|edge_case_type|description — zero duplicates.
  4. Splits: 80/10/10 train/validation/test, shuffled with seed 99.

Intended Use Cases

  • Fine-tuning code generation models to improve test quality
  • Benchmarking models on unit test generation
  • Educational examples of thorough edge case coverage
  • Augmenting existing test generation datasets

Limitations

  • Tests are syntactically correct but not guaranteed to run against the exact runtime environment (import paths, class context may need adaptation)
  • Java tests assume JUnit 4 test runner annotation style
  • Does not cover asynchronous patterns comprehensively (debounce/throttle examples are rudimentary)
  • Coverage per function is not exhaustive — 4–10 edge cases per function

License

Apache 2.0

Citation

@dataset{saluteface2026unittests,
  author    = {SalutefaceAAC},
  title     = {unit-test-edge-cases: Synthetic Unit Test Edge Cases Dataset},
  year      = {2026},
  publisher = {Hugging Face},
  url       = {https://huggingface.co/datasets/SalutefaceAAC/unit-test-edge-cases}
}
Downloads last month
31