File: test_xjson.cpp

package info (click to toggle)
xtensor 0.25.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 6,476 kB
  • sloc: cpp: 65,302; makefile: 202; python: 171; javascript: 8
file content (49 lines) | stat: -rw-r--r-- 1,717 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/***************************************************************************
 * Copyright (c) Johan Mabille, Sylvain Corlay and Wolf Vollprecht          *
 * Copyright (c) QuantStack                                                 *
 *                                                                          *
 * Distributed under the terms of the BSD 3-Clause License.                 *
 *                                                                          *
 * The full license is in the file LICENSE, distributed with this software. *
 ****************************************************************************/

#include <string>

#include "xtensor/xarray.hpp"
#include "xtensor/xjson.hpp"
#include "xtensor/xtensor.hpp"
#include "xtensor/xview.hpp"

#include "test_common_macros.hpp"

namespace xt
{
    TEST(xjson, xarray_to_json)
    {
        xt::xarray<double> t = {{{1, 2}, {3, 4}}, {{1, 2}, {3, 4}}};

        nlohmann::json jl = t;
        std::string s = jl.dump();
        EXPECT_EQ(s, "[[[1.0,2.0],[3.0,4.0]],[[1.0,2.0],[3.0,4.0]]]");
    }

    TEST(xjson, xarray_from_json)
    {
        nlohmann::json j = "[[[1.0,2.0],[3.0,4.0]],[[1.0,2.0],[3.0,4.0]]]"_json;
        auto arr = j.get<xt::xarray<double>>();
        auto ref = xt::xarray<double>({{{1, 2}, {3, 4}}, {{1, 2}, {3, 4}}});
        EXPECT_TRUE(all(equal(arr, ref)));
    }

    TEST(xjson, xview_from_json)
    {
        xt::xarray<double> arr = {{{1, 2}, {3, 4}}, {{1, 2}, {3, 4}}};

        auto v = xt::view(arr, 0);
        auto j = "[[10.0,10.0],[10.0,10.0]]"_json;
        from_json(j, v);

        auto ref = xt::xarray<double>({{{10, 10}, {10, 10}}, {{1, 2}, {3, 4}}});
        EXPECT_TRUE(all(equal(arr, ref)));
    }
}