| 1 | #![cfg(feature = "python_tests")] |
| 2 | |
| 3 | extern crate cpython; |
| 4 | #[macro_use] |
| 5 | extern crate quickcheck; |
| 6 | extern crate zbase32; |
| 7 | |
| 8 | mod common; |
| 9 | use common::*; |
| 10 | |
| 11 | use cpython::{Python, PyDict, PyResult, PyBytes}; |
| 12 | |
| 13 | quickcheck! { |
| 14 | fn encode(input: Vec<u8>) -> bool { |
| 15 | let bits = rand_bit_length(input.len(), 8); |
| 16 | let rust = zbase32::encode(&input, bits); |
| 17 | let python = py_encode(&input[..], Some(bits)).unwrap(); |
| 18 | rust == python |
| 19 | } |
| 20 | } |
| 21 | |
| 22 | quickcheck! { |
| 23 | fn decode(input: ZBaseEncodedData) -> bool { |
| 24 | let bits = rand_bit_length(input.len(), 5); |
| 25 | let rust = zbase32::decode(input.as_bytes(), bits).unwrap(); |
| 26 | let python = py_decode(&input.as_bytes()[..], Some(bits)).unwrap(); |
| 27 | rust == python |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | quickcheck! { |
| 32 | fn encode_bytes(input: Vec<u8>) -> bool { |
| 33 | let rust = zbase32::encode_full_bytes(&input); |
| 34 | let python = py_encode(&input[..], None).unwrap(); |
| 35 | rust == python |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | quickcheck! { |
| 40 | fn decode_bytes(input: ZBaseEncodedData) -> bool { |
| 41 | let rust = zbase32::decode_full_bytes(input.as_bytes()).unwrap(); |
| 42 | let python = py_decode(&input.as_bytes()[..], None).unwrap(); |
| 43 | rust == python |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | fn py_encode(input: &[u8], bits: Option<u64>) -> PyResult<String> { |
| 48 | let gil = Python::acquire_gil(); |
| 49 | let py = gil.python(); |
| 50 | let locals = PyDict::new(py); |
| 51 | locals.set_item(py, "pyzbase32", py.import("pyzbase32")?)?; |
| 52 | locals.set_item(py, "input", PyBytes::new(py, input))?; |
| 53 | let result: String = if let Some(bits) = bits { |
| 54 | locals.set_item(py, "bits", bits)?; |
| 55 | py.eval( |
| 56 | "pyzbase32.encode(input, bits).decode()", |
| 57 | None, |
| 58 | Some(&locals), |
| 59 | ) |
| 60 | } else { |
| 61 | py.eval( |
| 62 | "pyzbase32.encode_bytes(input).decode()", |
| 63 | None, |
| 64 | Some(&locals), |
| 65 | ) |
| 66 | }? |
| 67 | .extract(py)?; |
| 68 | Ok(result) |
| 69 | } |
| 70 | |
| 71 | fn py_decode(input: &[u8], bits: Option<u64>) -> PyResult<Vec<u8>> { |
| 72 | let gil = Python::acquire_gil(); |
| 73 | let py = gil.python(); |
| 74 | let locals = PyDict::new(py); |
| 75 | locals.set_item(py, "pyzbase32", py.import("pyzbase32")?)?; |
| 76 | locals.set_item(py, "input", PyBytes::new(py, input))?; |
| 77 | let result: PyBytes = if let Some(bits) = bits { |
| 78 | locals.set_item(py, "bits", bits)?; |
| 79 | py.eval("pyzbase32.decode(input, bits)", None, Some(&locals)) |
| 80 | } else { |
| 81 | py.eval("pyzbase32.decode_bytes(input)", None, Some(&locals)) |
| 82 | }? |
| 83 | .extract(py)?; |
| 84 | Ok(Vec::from(result.data(py))) |
| 85 | } |