]> Untitled Git - lemmy.git/blob - crates/apub/src/protocol/mod.rs
Reorganize federation tests (#2092)
[lemmy.git] / crates / apub / src / protocol / mod.rs
1 use activitystreams_kinds::object::ImageType;
2 use serde::{Deserialize, Serialize};
3 use url::Url;
4
5 use lemmy_apub_lib::values::MediaTypeMarkdown;
6 use lemmy_db_schema::newtypes::DbUrl;
7 use std::collections::HashMap;
8
9 pub mod activities;
10 pub(crate) mod collections;
11 pub(crate) mod objects;
12
13 #[derive(Clone, Debug, Deserialize, Serialize)]
14 #[serde(rename_all = "camelCase")]
15 pub struct Source {
16   pub(crate) content: String,
17   pub(crate) media_type: MediaTypeMarkdown,
18 }
19
20 impl Source {
21   pub(crate) fn new(content: String) -> Self {
22     Source {
23       content,
24       media_type: MediaTypeMarkdown::Markdown,
25     }
26   }
27 }
28
29 #[derive(Clone, Debug, Deserialize, Serialize)]
30 #[serde(rename_all = "camelCase")]
31 pub struct ImageObject {
32   #[serde(rename = "type")]
33   kind: ImageType,
34   pub(crate) url: Url,
35 }
36
37 impl ImageObject {
38   pub(crate) fn new(url: DbUrl) -> Self {
39     ImageObject {
40       kind: ImageType::Image,
41       url: url.into(),
42     }
43   }
44 }
45
46 #[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
47 #[serde(transparent)]
48 pub struct Unparsed(HashMap<String, serde_json::Value>);
49
50 #[cfg(test)]
51 pub(crate) mod tests {
52   use crate::context::WithContext;
53   use assert_json_diff::assert_json_include;
54   use lemmy_utils::LemmyError;
55   use serde::{de::DeserializeOwned, Serialize};
56   use std::{collections::HashMap, fs::File, io::BufReader};
57
58   pub(crate) fn file_to_json_object<T: DeserializeOwned>(path: &str) -> Result<T, LemmyError> {
59     let file = File::open(path)?;
60     let reader = BufReader::new(file);
61     Ok(serde_json::from_reader(reader)?)
62   }
63
64   pub(crate) fn test_json<T: DeserializeOwned>(path: &str) -> Result<WithContext<T>, LemmyError> {
65     file_to_json_object::<WithContext<T>>(path)
66   }
67
68   /// Check that json deserialize -> serialize -> deserialize gives identical file as initial one.
69   /// Ensures that there are no breaking changes in sent data.
70   pub(crate) fn test_parse_lemmy_item<T: Serialize + DeserializeOwned + std::fmt::Debug>(
71     path: &str,
72   ) -> Result<T, LemmyError> {
73     // parse file as T
74     let parsed = file_to_json_object::<T>(path)?;
75
76     // parse file into hashmap, which ensures that every field is included
77     let raw = file_to_json_object::<HashMap<String, serde_json::Value>>(path)?;
78     // assert that all fields are identical, otherwise print diff
79     assert_json_include!(actual: &parsed, expected: raw);
80     Ok(parsed)
81   }
82 }