subunit-0.2.1/.Cargo.toml.un~000064400000000000000000000064041046102023000141460ustar 00000000000000VimUnDolci$yuآDs9version = "0.2.0"dE*_dDBname = "subunit-rust"5_dDBname = "subunitrust"5_ dDg 3travis-ci = {repository = "mtreinish/subunit-rust"}5_ dDg *travis-ci = {repository = "/subunit-rust"}5_!dDn 8repository = "https://github.com/mtreinish/subunit-rust"5_!dDn /repository = "https://github.com//subunit-rust"5_dE)version = "0.2.0"5subunit-0.2.1/.github/dependabot.yml000064400000000000000000000007671046102023000155170ustar 00000000000000# To get started with Dependabot version updates, you'll need to specify which # package ecosystems to update and where the package manifests are located. # Please see the documentation for all configuration options: # https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates version: 2 updates: - package-ecosystem: "cargo" # See documentation for possible values directory: "/" # Location of package manifests schedule: interval: "daily" subunit-0.2.1/.github/workflows/main.yml000064400000000000000000000014021046102023000163560ustar 00000000000000--- name: CI on: push: branches: [ master ] pull_request: branches: [ master ] env: CARGO_TERM_COLOR: always jobs: build: runs-on: ${{ matrix.os }} strategy: matrix: os: ["ubuntu-latest", "macOS-latest", "windows-latest"] steps: - uses: actions/checkout@v2 - uses: actions-rs/toolchain@v1 with: toolchain: stable profile: minimal components: rustfmt - uses: actions/setup-python@v2 with: python-version: 3.8 - name: Build run: cargo build --verbose - name: Rust fmt run: cargo fmt -- --check - name: Clippy run: cargo clippy -- -D warnings - name: Install test deps run: cargo test --verbose --all subunit-0.2.1/.gitignore000064400000000000000000000000371046102023000133050ustar 00000000000000 /target **/*.rs.bk Cargo.lock subunit-0.2.1/Cargo.toml0000644000000017150000000000100105270ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] name = "subunit" version = "0.2.1" authors = ["Matthew Treinish "] description = "A subunit v2 protocol implementation in Rust" readme = "README.md" keywords = ["subunit"] categories = ["development-tools::testing"] license = "Apache-2.0" repository = "https://github.com/jelmer/subunit-rust" [dependencies.byteorder] version = "1.3" [dependencies.chrono] version = "0.4.11" [dependencies.crc32fast] version = "1.3" [badges.travis-ci] repository = "jelmer/subunit-rust" subunit-0.2.1/Cargo.toml.orig000064400000000000000000000007061046102023000142070ustar 00000000000000[package] name = "subunit" description = "A subunit v2 protocol implementation in Rust" version = "0.2.1" authors = ["Matthew Treinish "] license = "Apache-2.0" readme = "README.md" repository = "https://github.com/jelmer/subunit-rust" keywords = ["subunit"] categories = ["development-tools::testing"] [badges] travis-ci = {repository = "jelmer/subunit-rust"} [dependencies] chrono = "0.4.11" byteorder = "1.3" crc32fast = "1.3" subunit-0.2.1/LICENSE000064400000000000000000000236371046102023000123350ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. subunit-0.2.1/README.md000064400000000000000000000061371046102023000126030ustar 00000000000000Subunit Rust ============ [![subunit-rust on Travis CI][travis-image]][travis] [![subunit-rust on crates.io][cratesio-image]][cratesio] [![subunit-rust on Appveyor CI][appveyor-image]][appveyor] [travis-image]: https://travis-ci.org/mtreinish/subunit-rust.svg?branch=master [travis]: https://travis-ci.org/mtreinish/subunit-rust [cratesio-image]: https://img.shields.io/crates/v/subunit-rust.svg [cratesio]: https://crates.io/crates/subunit-rust [appveyor-image]: https://img.shields.io/appveyor/ci/mtreinish/subunit-rust/master.svg [appveyor]: https://ci.appveyor.com/project/mtreinish/subunit-rust This repo contains a implementation of the subunit v2 protocol in Rust. It provides an interface for both writing and reading subunit streams natively in rust. The subunit v2 protocol is documented in the [testing-cabal/subunit](https://github.com/testing-cabal/subunit/blob/master/README.rst#version-2) repository. ## Reading subunit packets Reading subunit packets first requires an object implementing the Read trait containing the subunit stream. The parse_subunit() function is used to first buffer the entire stream in memory, and then parse the contents and return a vector of Event structs. For example, parsing a subunit stream from a file: ```rust let mut f = File::open("results.subunit")?; let events = parse_subunit(f).unwrap(); ``` In this example, the `results.subunit` file will be opened and parsed with an Event struct in the events vector for each subunit packet in the file. ## Writing subunit packets Writing a subunit packet first requires creating an event structure to describe the contents of the packet. For example: ```rust let mut event_start = Event { status: Some("inprogress".to_string()), test_id: Some("A_test_id".to_string()), timestamp: Some(Utc.ymd(2014, 7, 8).and_hms(9, 10, 11)), tags: Some(vec!["tag_a".to_string(), "tag_b".to_string()]), file_content: None, file_name: None, mime_type: None, route_code: None }; ``` A typical test event normally involves 2 packets though, one to mark the start and the other to mark the finish of a test: ```rust let mut event_end = Event { status: Some("success".to_string()), test_id: Some("A_test_id".to_string()), timestamp: Some(Utc.ymd(2014, 7, 8).and_hms(9, 12, 0)), tags: Some(vec!["tag_a".to_string(), "tag_b".to_string()]), file_content: Some("stdout content".to_string().into_bytes()), file_name: Some("stdout:''".to_string()), mime_type: Some("text/plain;charset=utf8".to_string()), route_code: None }; ``` Then you'll want to write the packet out to something. Anything that implements the std::io::Write trait can be used for the packets, including things like a File and a TCPStream. In this case we'll use Vec to keep it in memory: ```rust let mut subunit_stream: Vec = Vec::new(); subunit_stream = event_start.write(subunit_stream)?; subunit_stream = event_end.write(subunit_stream)?; ``` With this the subunit_stream buffer will contain the contents of the subunit stream for that test event. subunit-0.2.1/src/.lib.rs.un~000064400000000000000000000261511046102023000141220ustar 00000000000000VimUnDoW,깆B;;`٪"GkBI dD_dD Result::Ok(value as u32)5_dD Result::Ok(value as u32)5_dD Result::Ok(value as u32)5_dD Result::Ok(value as u32)5_ dDL% if self.file_name.is_some() {5_0dDL; if let Some(file_name) = self.file_name.is_some() {5_0dDL4 if let Some(file_name) = self.file_name.() {5_ .dDL_ file_content = write_utf8(self.file_name.as_ref().unwrap(), file_content)?;5_ .dDL[ file_content = write_utf8(.file_name.as_ref().unwrap(), file_content)?;5_ 7dDLZ file_content = write_utf8(file_name.as_ref().unwrap(), file_content)?;5_ 7dDLY file_content = write_utf8(file_nameas_ref().unwrap(), file_content)?;5_ 7dDLS file_content = write_utf8(file_name().unwrap(), file_content)?;5_  7dDLP file_content = write_utf8(file_nameunwrap(), file_content)?;5_ 7dDLJ file_content = write_utf8(file_name(), file_content)?;5_7dDLI file_content = write_utf8(file_name), file_content)?;5_ dDL% match self.file_content {5_ dDM L5_ dD% match self.file_content {5_ dD; Option::None => (), // missing body is ok ?5_dD+ Option::Some(ref body) => {5_dD }5_ dD2 file_content.write_all(body)?;K file_content = write_number(len as u32, file_content)?;H let len = self.file_content.as_ref().unwrap().len();H file_content = write_utf8(file_name, file_content)?;5_ dDL self.file_content {5subunit-0.2.1/src/lib.rs000064400000000000000000000456031046102023000132300ustar 00000000000000// Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #![allow(clippy::cargo)] #![allow(clippy::unreadable_literal)] extern crate byteorder; extern crate chrono; extern crate crc32fast; use std::collections::HashSet; use std::error::Error; use std::fmt; use std::io::Cursor; use std::io::Read; use std::io::Write; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use chrono::prelude::*; #[derive(Debug, Clone)] pub struct SizeError; #[derive(Debug, Clone)] pub struct InvalidFlag; #[derive(Debug, Clone)] pub struct InvalidMask; type GenError = Box; type GenResult = Result; const SIGNATURE: u8 = 0xb3; impl fmt::Display for SizeError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Value is too large to encode") } } impl Error for SizeError { fn description(&self) -> &str { "Value is too large to encode" } fn cause(&self) -> Option<&dyn Error> { None } } impl fmt::Display for InvalidMask { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Mask code is invalid") } } impl Error for InvalidMask { fn description(&self) -> &str { "Mask code is valid" } fn cause(&self) -> Option<&dyn Error> { None } } impl fmt::Display for InvalidFlag { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "Flag code is invalid") } } impl Error for InvalidFlag { fn description(&self) -> &str { "Flag code is invalid" } fn cause(&self) -> Option<&dyn Error> { None } } fn flag_to_status(flag: u8) -> Result { match flag { 0x0 => Result::Ok("".to_string()), 0x1 => Result::Ok("exists".to_string()), 0x2 => Result::Ok("inprogress".to_string()), 0x3 => Result::Ok("success".to_string()), 0x4 => Result::Ok("uxsuccess".to_string()), 0x5 => Result::Ok("skip".to_string()), 0x6 => Result::Ok("fail".to_string()), 0x7 => Result::Ok("xfail".to_string()), _ => Result::Err(InvalidFlag), } } fn status_to_flag(status: &str) -> Result { if status.is_empty() { Result::Ok(0x0) } else if status == "exists" { Result::Ok(0x1) } else if status == "inprogress" { Result::Ok(0x2) } else if status == "success" { Result::Ok(0x3) } else if status == "uxsuccess" { Result::Ok(0x4) } else if status == "skip" { Result::Ok(0x5) } else if status == "fail" { Result::Ok(0x6) } else if status == "xfail" { Result::Ok(0x7) } else { Result::Err(InvalidFlag) } } fn flag_masks(masks: &str) -> Result { match masks { "testId" => Result::Ok(0x0800), "routeCode" => Result::Ok(0x0400), "timestamp" => Result::Ok(0x0200), "runnable" => Result::Ok(0x0100), "tags" => Result::Ok(0x0080), "mimeType" => Result::Ok(0x0020), "eof" => Result::Ok(0x0010), "fileContent" => Result::Ok(0x0040), _ => Result::Err(InvalidMask), } } fn flags_to_masks(flags: u16) -> GenResult> { let static_flags: [u16; 8] = [ 0x0800, 0x0400, 0x0200, 0x0100, 0x0080, 0x0020, 0x0010, 0x0040, ]; let mut masks: HashSet = HashSet::new(); for flag in static_flags.iter() { if flags & *flag != 0 { if *flag == 0x0800 { masks.insert("testId".to_string()); } else if *flag == 0x0400 { masks.insert("routeCode".to_string()); } else if *flag == 0x0200 { masks.insert("timestamp".to_string()); } else if *flag == 0x0100 { masks.insert("runnable".to_string()); } else if *flag == 0x0080 { masks.insert("tags".to_string()); } else if *flag == 0x0020 { masks.insert("mimeType".to_string()); } else if *flag == 0x0010 { masks.insert("eof".to_string()); } else if *flag == 0x0040 { masks.insert("fileContent".to_string()); } } } Result::Ok(masks) } fn write_number(value: u32, mut ret: T) -> GenResult { // The first two bits encode the size: // 00 = 1 byte // 01 = 2 bytes // 10 = 3 bytes // 11 = 4 bytes // 2^(8-2) if value < 64 { // Fits in one byte. ret.write_u8(value as u8)? // 2^(16-2): } else if value < 16384 { // Fits in two bytes. // Set the size to 01. ret.write_u16::(value as u16 | 0x4000)? // 2^(24-2): } else if value < 4194304 { // Fits in three bytes. // Drop the two least significant bytes and set the size to 10. ret.write_u8(((value >> 16) | 0x80) as u8)?; ret.write_u16::(value as u16)?; // 2^(32-2): } else if value < 1073741824 { // Fits in four bytes. // Set the size to 11. ret.write_u32::(value | 0xC0000000)?; } else { return Result::Err(Box::new(SizeError)); } Result::Ok(ret) } fn write_utf8(string: &str, mut out: T) -> GenResult { out = write_number(string.len() as u32, out)?; out.write_all(string.as_bytes())?; Result::Ok(out) } pub fn read_number(reader: &mut Cursor>) -> GenResult { let first = reader.read_u8()?; // Get 2 first bits for prefix let number_type = first & 0xc0; // Get last 6 bits for first octet let mut value = u32::from(first) & 0x3f; // 0b00, 1 octet if number_type == 0x00 { Result::Ok(value) // 0b01, 2octets } else if number_type == 0x40 { let suffix = reader.read_u8()?; value = (value << 8) | u32::from(suffix); Result::Ok(value) // 0b10, 3 octets } else if number_type == 0x80 { let suffix = reader.read_u16::()?; value = (value << 16) | u32::from(suffix); Result::Ok(value) // 0b11, 4 octets } else { let suffix = reader.read_u32::()?; value = (value << 24) | suffix; Result::Ok(value) } } fn read_utf8(reader: &mut Cursor>) -> GenResult { let length = read_number(reader)?; let mut bytes: Vec = Vec::new(); for _i in 0..length { let byte = reader.read_u8()?; bytes.push(byte) } let output = String::from_utf8(bytes)?; Result::Ok(output) } fn read_packet(cursor: &mut Cursor>) -> GenResult { let start_position = cursor.position(); let sig = cursor.read_u8()?; let flags = cursor.read_u16::()?; let packet_length = read_number(cursor)?; if sig != SIGNATURE { panic!("Invalid signature"); } let status = flag_to_status((flags & 0x0007) as u8)?; let masks = flags_to_masks(flags)?; let timestamp = if masks.contains("timestamp") { let seconds = cursor.read_u32::()?; let nanos = read_number(cursor)?; Some(Utc.timestamp(i64::from(seconds), nanos)) } else { None }; let test_id = if masks.contains("testId") { let id = read_utf8(cursor)?; Some(id) } else { None }; let tags = if masks.contains("tags") { let count = read_number(cursor)?; let mut tags_vec: Vec = Vec::new(); for _i in 0..count { let tag = read_utf8(cursor)?; tags_vec.push(tag); } Some(tags_vec) } else { None }; let mime_type = if masks.contains("mimeType") { let mime = read_utf8(cursor)?; Some(mime) } else { None }; let file_content; let file_name; if masks.contains("fileContent") { let name = read_utf8(cursor)?; file_name = Some(name); let file_length = read_number(cursor)?; let mut content: Vec = Vec::new(); for _i in 0..file_length { let byte = cursor.read_u8()?; content.push(byte); } file_content = Some(content); } else { file_content = None; file_name = None; } let route_code = if masks.contains("routeCode") { let code = read_utf8(cursor)?; Some(code) } else { None }; let _crc32 = cursor.read_u32::()?; let end_position = cursor.position(); if u64::from(packet_length) != (end_position - start_position) { panic!("Packet length doesn't match"); } let event = Event { status: Some(status), test_id, timestamp, tags, file_content, file_name, mime_type, route_code, }; Result::Ok(event) } pub fn parse_subunit(mut reader: T) -> GenResult> { let mut output: Vec = Vec::new(); let mut contents: Vec = Vec::new(); reader.read_to_end(&mut contents)?; let stream_length = contents.len() as u64; let cursor = &mut Cursor::new(contents); while cursor.position() < stream_length { let packet = read_packet(cursor)?; output.push(packet); } Result::Ok(output) } pub struct Event { pub status: Option, pub test_id: Option, pub timestamp: Option>, pub file_name: Option, pub file_content: Option>, pub mime_type: Option, pub route_code: Option, pub tags: Option>, } impl Event { pub fn write(&mut self, mut writer: T) -> GenResult { // PACKET = SIGNATURE FLAGS PACKET_LENGTH TIMESTAMP? TESTID? TAGS? // MIME? FILECONTENT? ROUTING_CODE? CRC32 let flags = self.make_flags()?; let timestamp = self.make_timestamp()?; let test_id = self.make_test_id()?; let tags = self.make_tags()?; let mime_type = self.make_mime_type()?; let file_content = self.make_file_content()?; let routing_code = self.make_routing_code()?; let mut buffer: Vec = Vec::new(); let mut body_length = timestamp.len() + test_id.len() + tags.len(); body_length += mime_type.len() + file_content.len(); body_length += routing_code.len(); // baseLength = header (minus variant length) + body + crc32 let base_length = 3 + body_length + 4; // length of length depends on baseLength and its own length // 63 - 1 let length; if base_length <= 62 { length = base_length + 1; // 16383 - 2 } else if base_length <= 16381 { length = base_length + 2; // 4194303 - 3 } else if base_length <= 4194300 { length = base_length + 3; } else { panic!("The packet is too large"); } // Write event to stream buffer.write_u8(SIGNATURE)?; buffer.write_u16::(flags)?; buffer = write_number(length as u32, buffer)?; buffer.write_all(×tamp)?; buffer.write_all(&test_id)?; buffer.write_all(&tags)?; buffer.write_all(&mime_type)?; buffer.write_all(&file_content)?; buffer.write_all(&routing_code)?; // Flush buffer into output and digest to calculate crc32 let checksum = crc32fast::hash(&buffer); writer.write_all(&buffer)?; writer.write_u32::(checksum)?; Result::Ok(writer) } fn make_routing_code(&self) -> GenResult> { let mut routing_code: Vec = Vec::new(); if self.route_code.is_some() { routing_code = write_utf8(self.route_code.as_ref().unwrap(), routing_code)?; } Result::Ok(routing_code) } fn make_file_content(&self) -> GenResult> { let mut file_content: Vec = Vec::new(); if let Some(file_name) = self.file_name.as_ref() { if let Option::Some(ref body) = self.file_content { file_content = write_utf8(file_name, file_content)?; let len = self.file_content.as_ref().unwrap().len(); file_content = write_number(len as u32, file_content)?; file_content.write_all(body)?; } } Result::Ok(file_content) } fn make_mime_type(&self) -> GenResult> { let mut mime_type: Vec = Vec::new(); if self.mime_type.is_some() { mime_type = write_utf8(self.mime_type.as_ref().unwrap(), mime_type)?; } Result::Ok(mime_type) } fn make_tags(&self) -> GenResult> { let mut tags: Vec = Vec::new(); if self.tags.is_some() { let len = self.tags.as_ref().unwrap().len(); tags = write_number(len as u32, tags)?; for tag in self.tags.as_ref().unwrap() { tags = write_utf8(tag, tags)?; } } Result::Ok(tags) } fn make_test_id(&self) -> GenResult> { let mut test_id: Vec = Vec::new(); if self.test_id.is_some() { let raw_id = self.test_id.as_ref().unwrap(); test_id = write_utf8(raw_id, test_id)?; } Result::Ok(test_id) } fn make_timestamp(&self) -> GenResult> { let mut timestamp: Vec = Vec::new(); if self.timestamp.is_some() { let secs = self.timestamp.unwrap().timestamp() as u32; timestamp.write_u32::(secs)?; let subsec_nanos = self.timestamp.unwrap().timestamp_subsec_nanos(); timestamp = write_number(subsec_nanos, timestamp)?; } Result::Ok(timestamp) } fn make_flags(&self) -> GenResult { let mut flags = 0x2000_u16; // version 0x2 if self.status.is_some() { flags |= status_to_flag(self.status.as_ref().unwrap())?; } if self.timestamp.is_some() { flags |= flag_masks("timestamp")?; } if self.test_id.is_some() { flags |= flag_masks("testId")?; } if self.tags.is_some() { flags |= flag_masks("tags")?; } if self.mime_type.is_some() { flags |= flag_masks("mimeType")?; } if self.file_name.is_some() && self.file_content.is_some() { flags |= flag_masks("fileContent")?; } if self.route_code.is_some() { flags |= flag_masks("routeCode")?; } Result::Ok(flags) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_write_event() { let mut event = Event { status: Some("inprogress".to_string()), test_id: Some("A_test_id".to_string()), timestamp: Some(Utc.ymd(2014, 7, 8).and_hms(9, 10, 11)), tags: Some(vec!["tag_a".to_string(), "tag_b".to_string()]), file_content: None, file_name: None, mime_type: None, route_code: None, }; let mut buffer: Vec = Vec::new(); // use std::fs::File; // let mut buffer = File::create("/tmp/test.subunit").unwrap(); buffer = match event.write(buffer) { Result::Ok(buffer) => buffer, Result::Err(err) => panic!("Error while generating subunit {}", err), }; let cursor = Cursor::new(buffer); let out_events = parse_subunit(cursor); let out_event = out_events.unwrap().pop().unwrap(); assert_eq!(event.test_id, out_event.test_id); assert_eq!(event.status, out_event.status); assert_eq!(event.timestamp, out_event.timestamp); assert_eq!(event.tags, out_event.tags); assert_eq!(event.file_content, out_event.file_content); assert_eq!(event.file_name, out_event.file_name); assert_eq!(event.mime_type, out_event.mime_type); assert_eq!(event.route_code, out_event.route_code); } #[test] fn test_write_full_test_event_with_file_content() { let mut event = Event { status: Some("inprogress".to_string()), test_id: Some("A_test_id".to_string()), timestamp: Some(Utc.ymd(2014, 7, 8).and_hms(9, 10, 11)), tags: Some(vec!["tag_a".to_string(), "tag_b".to_string()]), file_content: Some("stdout content".to_string().into_bytes()), file_name: Some("stdout:''".to_string()), mime_type: Some("text/plain;charset=utf8".to_string()), route_code: None, }; let mut event_a = Event { status: Some("fail".to_string()), test_id: Some("A_test_id".to_string()), timestamp: Some(Utc.ymd(2014, 7, 8).and_hms(9, 12, 1)), tags: Some(vec!["tag_a".to_string(), "tag_b".to_string()]), file_content: None, file_name: None, mime_type: None, route_code: None, }; let mut buffer: Vec = Vec::new(); // use std::fs::File; // let mut buffer = File::create("/tmp/test2.subunit").unwrap(); buffer = match event.write(buffer) { Result::Ok(buffer) => buffer, Result::Err(err) => panic!("Error while generating subunit {}", err), }; buffer = match event_a.write(buffer) { Result::Ok(buffer) => buffer, Result::Err(err) => panic!("Error while generating subunit {}", err), }; let cursor = Cursor::new(buffer); let mut out_events = parse_subunit(cursor).unwrap(); // Parse last packet let out_event_a = out_events.pop().unwrap(); assert_eq!(event_a.test_id, out_event_a.test_id); assert_eq!(event_a.status, out_event_a.status); assert_eq!(event_a.timestamp, out_event_a.timestamp); assert_eq!(event_a.tags, out_event_a.tags); assert_eq!(event_a.file_content, out_event_a.file_content); assert_eq!(event_a.file_name, out_event_a.file_name); assert_eq!(event_a.mime_type, out_event_a.mime_type); assert_eq!(event_a.route_code, out_event_a.route_code); // Parse first packet let out_event = out_events.pop().unwrap(); assert_eq!(event.test_id, out_event.test_id); assert_eq!(event.status, out_event.status); assert_eq!(event.timestamp, out_event.timestamp); assert_eq!(event.tags, out_event.tags); assert_eq!(event.file_content, out_event.file_content); assert_eq!(event.file_name, out_event.file_name); assert_eq!(event.mime_type, out_event.mime_type); assert_eq!(event.route_code, out_event.route_code); } }