22301080 | a033473 | 2025-05-17 21:38:32 +0800 | [diff] [blame^] | 1 | import com.turn.ttorrent.bcodec.BDecoder; |
| 2 | import com.turn.ttorrent.bcodec.InvalidBEncodingException; |
| 3 | import org.testng.annotations.Test; |
| 4 | |
| 5 | import java.io.IOException; |
| 6 | import java.io.UnsupportedEncodingException; |
| 7 | import java.nio.ByteBuffer; |
| 8 | |
| 9 | import static org.testng.Assert.assertEquals; |
| 10 | import static org.testng.Assert.fail; |
| 11 | |
| 12 | public class BDecoderTest { |
| 13 | |
| 14 | @Test |
| 15 | public void testDecodeNumbers() throws IOException { |
| 16 | |
| 17 | testNumber(0); |
| 18 | testNumber(1); |
| 19 | testNumber(Integer.MAX_VALUE); |
| 20 | testNumber(1234567); |
| 21 | testNumber(-1); |
| 22 | testNumber(-100); |
| 23 | testNumber(Integer.MIN_VALUE); |
| 24 | testNumber(Long.MAX_VALUE); |
| 25 | testNumber(Long.MIN_VALUE); |
| 26 | |
| 27 | //by specification number with lead zero it's incorrect value |
| 28 | testBadNumber("00"); |
| 29 | testBadNumber("01234"); |
| 30 | testBadNumber("000"); |
| 31 | testBadNumber("0001"); |
| 32 | |
| 33 | } |
| 34 | |
| 35 | private void testBadNumber(String number) throws IOException { |
| 36 | try { |
| 37 | BDecoder.bdecode(numberToBEPBytes(number)); |
| 38 | } catch (InvalidBEncodingException e) { |
| 39 | return; |
| 40 | } |
| 41 | fail("Value " + number + " is incorrect by BEP specification but is was parsed correctly"); |
| 42 | } |
| 43 | |
| 44 | private void testNumber(long value) throws IOException { |
| 45 | assertEquals(BDecoder.bdecode(numberToBEPBytes(value)).getLong(), value); |
| 46 | } |
| 47 | |
| 48 | private ByteBuffer numberToBEPBytes(long value) throws UnsupportedEncodingException { |
| 49 | return ByteBuffer.wrap(("i" + value + "e").getBytes("ASCII")); |
| 50 | } |
| 51 | |
| 52 | private ByteBuffer numberToBEPBytes(String value) throws UnsupportedEncodingException { |
| 53 | return ByteBuffer.wrap(("i" + value + "e").getBytes("ASCII")); |
| 54 | } |
| 55 | |
| 56 | } |