implement get chaining, cover by tests

This commit is contained in:
mykola2312 2024-10-14 18:33:24 +03:00
parent 945506dcfc
commit 43da5e8d45
3 changed files with 26 additions and 9 deletions

View file

@ -41,13 +41,12 @@ public class BDict extends BList {
}
@SuppressWarnings("unchecked")
public <T extends BValue> T get(String key) throws BValueError {
T value = (T)get(new BString(key));
System.out.println("sedsed " + value.getClass().getName());
if (!(value instanceof T)) {
throw new BErrorValueCast(this, key, value.getClass());
public <T extends BValue> T get(BType type, String key) throws BValueError {
BValue value = get(new BString(key));
if (!value.getType().equals(type)) {
throw new BErrorValueCast(this, key, type, value.getType());
}
return value;
return (T)value;
}
}

View file

@ -1,11 +1,12 @@
package com.mykola2312.retracker.bencode.error;
import com.mykola2312.retracker.bencode.BType;
import com.mykola2312.retracker.bencode.BValue;
public class BErrorValueCast extends BValueError {
private static final long serialVersionUID = 6790204193944478194L;
public BErrorValueCast(BValue node, String key, Class cause) {
super(node, String.format("cast error: %s is instance of %s", key, cause.getName()));
public BErrorValueCast(BValue node, String key, BType wanted, BType found) {
super(node, String.format("cast error: %s is type %s instead of %s", key, found, wanted));
}
}

View file

@ -4,6 +4,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import org.junit.jupiter.api.Test;
@ -52,7 +53,23 @@ public class BDictTest {
dict.set("key", new BInteger(4));
assertThrows(BErrorValueCast.class, () -> {
dict.<BString>get("key").get();
dict.<BString>get(BType.STRING, "key");
});
}
@Test
public void testGetChained() {
BDict dict = new BDict()
.set("first", new BDict()
.set("second", new BInteger(3)));
assertDoesNotThrow(() -> {
BInteger value = dict
.<BDict>get(BType.DICT, "first")
.<BInteger>get(BType.INTEGER, "second");
assertNotNull(value);
assertEquals(value, new BInteger(3));
});
}
}