Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement battery item type #32141

Merged
merged 19 commits into from
Jul 15, 2019
Next Next commit
add unit values for loading energy strings
  • Loading branch information
ymber committed Jul 9, 2019
commit b7fc135a4eaa587f90dc5453248da16572952e8e
10 changes: 10 additions & 0 deletions src/units.h
Original file line number Diff line number Diff line change
Expand Up @@ -490,6 +490,16 @@ inline constexpr units::quantity<double, units::energy_in_millijoule_tag> operat
return units::from_kilojoule( v );
}

namespace units
{
static const std::vector<std::pair<std::string, energy>> energy_units = { {
{ "mJ", 1_mJ },
{ "J", 1_J },
{ "kJ", 1_kJ },
}
};
}

template<typename T>
T read_from_json_string( JsonIn &jsin, const std::vector<std::pair<std::string, T>> &units )
{
Expand Down
34 changes: 34 additions & 0 deletions tests/energy_units_test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#include <sstream>
#include <string>

#include "catch/catch.hpp"
#include "json.h"
#include "units.h"

static units::energy parse_energy_quantity( const std::string &json )
{
std::istringstream buffer( json );
JsonIn jsin( buffer );
return read_from_json_string<units::energy>( jsin, units::energy_units );
}

TEST_CASE( "energy parsing from JSON" )
{
CHECK_THROWS( parse_energy_quantity( "\"\"" ) ); // empty string
CHECK_THROWS( parse_energy_quantity( "27" ) ); // not a string at all
CHECK_THROWS( parse_energy_quantity( "\" \"" ) ); // only spaces
CHECK_THROWS( parse_energy_quantity( "\"27\"" ) ); // no energy unit

REQUIRE( parse_energy_quantity( "\"1 mJ\"" ) == 1_mJ );
REQUIRE( parse_energy_quantity( "\"1 J\"" ) == 1_J );
REQUIRE( parse_energy_quantity( "\"1 kJ\"" ) == 1_kJ );
REQUIRE( parse_energy_quantity( "\"+1 mJ\"" ) == 1_mJ );
REQUIRE( parse_energy_quantity( "\"+1 J\"" ) == 1_J );
REQUIRE( parse_energy_quantity( "\"+1 kJ\"" ) == 1_kJ );

REQUIRE( parse_energy_quantity( "\"1 mJ 1 J 1 kJ\"" ) == 1_mJ + 1_J + 1_kJ );
REQUIRE( parse_energy_quantity( "\"1 mJ -4 J 1 kJ\"" ) == 1_mJ - 4_J + 1_kJ );

REQUIRE( 1_mJ * 1000 == units::from_joule( 1 ) );
REQUIRE( 1_J * 1000 == units::from_kilojoule( 1 ) );
}