Skip to main content

fritz_sim/
fixture.rs

1//! Fixtures: devices recorded with `fritz capture` and anonymized.
2
3use std::collections::{BTreeMap, HashMap};
4use std::fs;
5use std::io;
6use std::path::{Path, PathBuf};
7
8use serde_json::Value;
9use tr064::{DeviceDescription, Scpd};
10
11/// The files of the fixtures that come with this crate, embedded by
12/// `build.rs`, by path like `fritzbox-7690/8.25/tr64desc.xml`.
13static BUNDLED: &[(&str, &str)] = include!(concat!(env!("OUT_DIR"), "/bundled.rs"));
14
15/// Why a fixture cannot be loaded.
16#[derive(Debug, thiserror::Error)]
17pub enum Error {
18    #[error("cannot read {}", path.display())]
19    Io {
20        path: PathBuf,
21        #[source]
22        source: io::Error,
23    },
24    #[error("{} is not valid: {reason}", path.display())]
25    Invalid { path: PathBuf, reason: String },
26    #[error("no fixture {0} comes with fritz-sim")]
27    Unknown(String),
28}
29
30/// A recorded answer to an action call.
31#[derive(Debug, Clone, PartialEq, Eq)]
32pub enum Answer {
33    /// The output arguments by name.
34    Ok(BTreeMap<String, String>),
35    /// A UPnP error.
36    Fault { code: u16, description: String },
37}
38
39/// The recorded answers to one action: to a call without index, or to the
40/// calls with each index.
41#[derive(Debug, Clone, Default)]
42pub(crate) struct Recording {
43    pub(crate) once: Option<Answer>,
44    pub(crate) indexed: BTreeMap<u32, Answer>,
45}
46
47/// A device as recorded in a fixture directory:
48///
49/// ```text
50/// tr64desc.xml
51/// scpd/<file>.xml
52/// responses/<service>/<action>[@<index>].json
53/// lists/<name>.<xml|json>
54/// api/<path>.json
55/// ```
56///
57/// A list document `lists/devicehostlist.xml` is served at the path
58/// `/devicehostlist.lua` that an action like `X_AVM-DE_GetHostListPath`
59/// returns. A document `api/v0/smarthome/overview.json` of the REST API is
60/// served at `/api/v0/smarthome/overview`.
61#[derive(Debug, Clone)]
62pub struct Fixture {
63    pub(crate) description_xml: String,
64    pub(crate) description: DeviceDescription,
65    /// The service descriptions by file name, like `hostsSCPD.xml`.
66    pub(crate) scpds: HashMap<String, (String, Scpd)>,
67    /// The recorded answers by service, like `Hosts1`, and action.
68    pub(crate) recordings: HashMap<(String, String), Recording>,
69    /// The list documents by name, like `devicehostlist`.
70    pub(crate) lists: HashMap<String, String>,
71    /// The documents of the REST API by path, like
72    /// `/api/v0/smarthome/overview`.
73    pub(crate) api: HashMap<String, String>,
74}
75
76impl Fixture {
77    /// Loads a fixture that comes with this crate, by name like
78    /// `fritzbox-7690/8.25`. The fixtures are part of the crate, so this
79    /// reads no files. See [`Fixture::bundled_names`].
80    ///
81    /// # Errors
82    ///
83    /// [`Error::Unknown`] if no fixture has the name.
84    pub fn bundled(name: &str) -> Result<Self, Error> {
85        if !Self::bundled_names().iter().any(|n| n == name) {
86            return Err(Error::Unknown(name.to_owned()));
87        }
88        Self::read(Source::Bundled, Path::new(name))
89    }
90
91    /// The names of the fixtures that come with this crate, sorted, like
92    /// `fritzbox-7690/8.25`. Tests can run against each of them.
93    pub fn bundled_names() -> Vec<String> {
94        let mut names: Vec<String> = BUNDLED
95            .iter()
96            .filter_map(|(path, _)| {
97                let mut parts = path.splitn(3, '/');
98                Some(format!("{}/{}", parts.next()?, parts.next()?))
99            })
100            .collect();
101        names.dedup();
102        names
103    }
104
105    /// Loads the fixture in `dir`.
106    ///
107    /// # Errors
108    ///
109    /// The errors of reading the files, and [`Error::Invalid`] if one of
110    /// them cannot be parsed.
111    pub fn load(dir: impl AsRef<Path>) -> Result<Self, Error> {
112        Self::read(Source::Disk, dir.as_ref())
113    }
114
115    /// Reads the fixture in `dir` of `source`.
116    fn read(source: Source, dir: &Path) -> Result<Self, Error> {
117        let read = |path: &Path| source.read(path);
118        let entries = |dir: &Path| source.entries(dir);
119        let path = dir.join("tr64desc.xml");
120        let description_xml = read(&path)?;
121        let description = DeviceDescription::parse(&description_xml).map_err(invalid(&path))?;
122        let mut scpds = HashMap::new();
123        for (name, path) in entries(&dir.join("scpd"))? {
124            let xml = read(&path)?;
125            let scpd = Scpd::parse(&xml).map_err(invalid(&path))?;
126            scpds.insert(name, (xml, scpd));
127        }
128        let mut recordings: HashMap<_, Recording> = HashMap::new();
129        for (service, service_dir) in entries(&dir.join("responses"))? {
130            for (name, path) in entries(&service_dir)? {
131                let Some(stem) = name.strip_suffix(".json") else {
132                    continue;
133                };
134                let (action, index) = match stem.split_once('@') {
135                    Some((action, index)) => {
136                        let index = index.parse().map_err(invalid(&path))?;
137                        (action, Some(index))
138                    }
139                    None => (stem, None),
140                };
141                let Some(answer) = answer(&read(&path)?).map_err(invalid(&path))? else {
142                    continue;
143                };
144                let recording = recordings
145                    .entry((service.clone(), action.to_owned()))
146                    .or_default();
147                match index {
148                    Some(index) => {
149                        recording.indexed.insert(index, answer);
150                    }
151                    None => recording.once = Some(answer),
152                }
153            }
154        }
155        let mut lists = HashMap::new();
156        let lists_dir = dir.join("lists");
157        if source.is_dir(&lists_dir) {
158            for (name, path) in entries(&lists_dir)? {
159                let name = name.split_once('.').map_or(name.as_str(), |(stem, _)| stem);
160                lists.insert(name.to_owned(), read(&path)?);
161            }
162        }
163        let mut api = HashMap::new();
164        let api_dir = dir.join("api");
165        if source.is_dir(&api_dir) {
166            documents(source, &api_dir, "/api", &mut api)?;
167        }
168        Ok(Self {
169            description_xml,
170            description,
171            scpds,
172            recordings,
173            lists,
174            api,
175        })
176    }
177
178    /// The device description.
179    pub fn description(&self) -> &DeviceDescription {
180        &self.description
181    }
182
183    /// The recorded answer to a call of `action` of the service `service`,
184    /// like `Hosts1`, with the given index or without one.
185    pub fn answer(&self, service: &str, action: &str, index: Option<u32>) -> Option<&Answer> {
186        let recording = self
187            .recordings
188            .get(&(service.to_owned(), action.to_owned()))?;
189        match index {
190            Some(index) => recording.indexed.get(&index),
191            None => recording.once.as_ref(),
192        }
193    }
194
195    /// Records `answer` for calls of `action` of the service `service`,
196    /// like `Hosts1`, with the given index or without one, in place of a
197    /// recorded answer. For tests of answers the fixture lacks.
198    #[must_use]
199    pub fn with_answer(
200        mut self,
201        service: &str,
202        action: &str,
203        index: Option<u32>,
204        answer: Answer,
205    ) -> Self {
206        let recording = self
207            .recordings
208            .entry((service.to_owned(), action.to_owned()))
209            .or_default();
210        match index {
211            Some(index) => {
212                recording.indexed.insert(index, answer);
213            }
214            None => recording.once = Some(answer),
215        }
216        self
217    }
218}
219
220/// Parses a recorded answer: `{"status": "ok", "out": {…}}` or
221/// `{"status": "fault", "code": 714, "description": "…"}`. Calls that failed
222/// without an answer, `{"status": "failed", …}`, count as not recorded.
223fn answer(json: &str) -> Result<Option<Answer>, String> {
224    let value: Value = serde_json::from_str(json).map_err(|e| e.to_string())?;
225    match value["status"].as_str() {
226        Some("ok") => {
227            let out = value["out"].as_object().ok_or("no output arguments")?;
228            out.iter()
229                .map(|(name, value)| {
230                    let value = value.as_str().ok_or(format!("{name} is not a string"))?;
231                    Ok((name.clone(), value.to_owned()))
232                })
233                .collect::<Result<_, String>>()
234                .map(|out| Some(Answer::Ok(out)))
235        }
236        Some("fault") => {
237            let code = value["code"].as_u64().and_then(|c| u16::try_from(c).ok());
238            Ok(Some(Answer::Fault {
239                code: code.ok_or("no error code")?,
240                description: value["description"].as_str().unwrap_or_default().to_owned(),
241            }))
242        }
243        Some("failed") => Ok(None),
244        _ => Err("unknown status".to_owned()),
245    }
246}
247
248/// Adds the JSON documents in `dir` and its subdirectories to `found`, by
249/// their path under `prefix` without the extension.
250fn documents(
251    source: Source,
252    dir: &Path,
253    prefix: &str,
254    found: &mut HashMap<String, String>,
255) -> Result<(), Error> {
256    for (name, path) in source.entries(dir)? {
257        if source.is_dir(&path) {
258            documents(source, &path, &format!("{prefix}/{name}"), found)?;
259        } else if let Some(stem) = name.strip_suffix(".json") {
260            found.insert(format!("{prefix}/{stem}"), source.read(&path)?);
261        }
262    }
263    Ok(())
264}
265
266/// Where the files of a fixture come from.
267#[derive(Debug, Clone, Copy)]
268enum Source {
269    /// The file system.
270    Disk,
271    /// The fixtures embedded in the crate, with paths relative to them.
272    Bundled,
273}
274
275impl Source {
276    fn read(self, path: &Path) -> Result<String, Error> {
277        match self {
278            Self::Disk => fs::read_to_string(path).map_err(|source| Error::Io {
279                path: path.to_owned(),
280                source,
281            }),
282            Self::Bundled => Ok(bundled(path).next().map_or("", |(_, c)| c).to_owned()),
283        }
284    }
285
286    fn is_dir(self, path: &Path) -> bool {
287        match self {
288            Self::Disk => path.is_dir(),
289            Self::Bundled => bundled(path).any(|(p, _)| p != path),
290        }
291    }
292
293    /// The entries of a directory by name, without hidden ones like
294    /// `.DS_Store`.
295    fn entries(self, dir: &Path) -> Result<Vec<(String, PathBuf)>, Error> {
296        let mut entries = Vec::new();
297        match self {
298            Self::Disk => {
299                let io_error = |source| Error::Io {
300                    path: dir.to_owned(),
301                    source,
302                };
303                for entry in fs::read_dir(dir).map_err(io_error)? {
304                    let entry = entry.map_err(io_error)?;
305                    let name = entry.file_name().to_string_lossy().into_owned();
306                    if !name.starts_with('.') {
307                        entries.push((name, entry.path()));
308                    }
309                }
310            }
311            Self::Bundled => {
312                let below = |(path, _): (&'static Path, _)| path.strip_prefix(dir).ok();
313                for first in bundled(dir)
314                    .filter_map(below)
315                    .filter_map(|p| p.iter().next())
316                {
317                    let name = first.to_string_lossy().into_owned();
318                    if !entries.iter().any(|(n, _)| *n == name) {
319                        entries.push((name.clone(), dir.join(name)));
320                    }
321                }
322            }
323        }
324        Ok(entries)
325    }
326}
327
328/// The embedded files at or below `path`, with their paths.
329fn bundled(path: &Path) -> impl Iterator<Item = (&'static Path, &'static str)> {
330    BUNDLED
331        .iter()
332        .map(|(p, content)| (Path::new(*p), *content))
333        .filter(move |(p, _)| p.starts_with(path))
334}
335
336fn invalid<E: ToString>(path: &Path) -> impl FnOnce(E) -> Error {
337    let path = path.to_owned();
338    move |error| Error::Invalid {
339        path,
340        reason: error.to_string(),
341    }
342}
343
344#[cfg(test)]
345mod tests {
346    use super::*;
347
348    #[test]
349    fn parses_answers() {
350        assert_eq!(
351            answer(r#"{"status": "ok", "out": {"NewEnable": "1"}}"#),
352            Ok(Some(Answer::Ok(BTreeMap::from([(
353                "NewEnable".to_owned(),
354                "1".to_owned()
355            )]))))
356        );
357        assert_eq!(
358            answer(r#"{"status": "fault", "code": 714}"#),
359            Ok(Some(Answer::Fault {
360                code: 714,
361                description: String::new()
362            }))
363        );
364        assert_eq!(
365            answer(r#"{"status": "failed", "error": "timeout"}"#),
366            Ok(None)
367        );
368        for (json, error) in [
369            ("{", "EOF while parsing an object at line 1 column 1"),
370            (r#"{"status": "ok"}"#, "no output arguments"),
371            (
372                r#"{"status": "ok", "out": {"NewEnable": 1}}"#,
373                "NewEnable is not a string",
374            ),
375            (r#"{"status": "fault", "code": 70000}"#, "no error code"),
376            (r#"{"status": "skipped"}"#, "unknown status"),
377        ] {
378            assert_eq!(answer(json), Err(error.to_owned()), "{json}");
379        }
380    }
381}