From 111bcbcd2ce79c267295097ff1ba62a59e6a5930 Mon Sep 17 00:00:00 2001
From: James Skimming <647706+JSkimming@users.noreply.github.com>
Date: Sun, 29 Dec 2019 16:02:33 +0000
Subject: [PATCH 1/5] Added support for nullable reference types
---
src/Tesla.NET/Models/IChargeState.cs | 10 +++---
src/Tesla.NET/Models/IDriveState.cs | 4 +--
.../Models/IMessageResponse.Generic.cs | 2 +-
src/Tesla.NET/Models/IMessageResponse.cs | 2 +-
src/Tesla.NET/Models/IVehicle.cs | 16 ++++-----
src/Tesla.NET/Models/IVehicleState.cs | 14 ++++----
src/Tesla.NET/Models/Internal/ChargeState.cs | 20 +++++------
src/Tesla.NET/Models/Internal/DriveState.cs | 8 ++---
.../Models/Internal/MessageResponse.cs | 8 ++---
src/Tesla.NET/Models/Internal/Vehicle.cs | 34 +++++++++----------
src/Tesla.NET/Models/Internal/VehicleState.cs | 28 +++++++--------
.../Requests/HttpClientExtensions.cs | 18 +++++-----
src/Tesla.NET/Tesla.NET.csproj | 1 +
src/Tesla.NET/TeslaClientBase.Disposable.cs | 5 +--
src/Tesla.NET/TeslaClientBase.cs | 11 +++---
test/Tesla.NET.Tests/Tesla.NET.Tests.csproj | 1 +
16 files changed, 90 insertions(+), 92 deletions(-)
diff --git a/src/Tesla.NET/Models/IChargeState.cs b/src/Tesla.NET/Models/IChargeState.cs
index 67eb26c..da029d7 100644
--- a/src/Tesla.NET/Models/IChargeState.cs
+++ b/src/Tesla.NET/Models/IChargeState.cs
@@ -15,19 +15,19 @@ public interface IChargeState : IState
/// Gets the charging state of a .
///
[JsonProperty("charging_state")]
- string ChargingState { get; }
+ string? ChargingState { get; }
///
/// Gets the type of fast charging.
///
[JsonProperty("fast_charger_type")]
- string FastChargerType { get; }
+ string? FastChargerType { get; }
///
/// Gets the brand of fast charging.
///
[JsonProperty("fast_charger_brand")]
- string FastChargerBrand { get; }
+ string? FastChargerBrand { get; }
///
/// Gets the charge limit .
@@ -171,7 +171,7 @@ public interface IChargeState : IState
/// Gets the type of the charge cable connected to a .
///
[JsonProperty("conn_charge_cable")]
- string ConnChargeCable { get; }
+ string? ConnChargeCable { get; }
///
/// Gets the schedule charging start time of a .
@@ -213,7 +213,7 @@ public interface IChargeState : IState
/// Gets the charge port latch of a .
///
[JsonProperty("charge_port_latch")]
- string ChargePortLatch { get; }
+ string? ChargePortLatch { get; }
///
/// Gets the charge current request of a .
diff --git a/src/Tesla.NET/Models/IDriveState.cs b/src/Tesla.NET/Models/IDriveState.cs
index c8fdd47..488305e 100644
--- a/src/Tesla.NET/Models/IDriveState.cs
+++ b/src/Tesla.NET/Models/IDriveState.cs
@@ -15,13 +15,13 @@ public interface IDriveState : IState
/// Gets the shift state of a .
///
[JsonProperty("shift_state")]
- string ShiftState { get; }
+ string? ShiftState { get; }
///
/// Gets the speed .
///
[JsonProperty("speed")]
- string Speed { get; }
+ string? Speed { get; }
///
/// Gets the power .
diff --git a/src/Tesla.NET/Models/IMessageResponse.Generic.cs b/src/Tesla.NET/Models/IMessageResponse.Generic.cs
index d7baa7d..8fe999a 100644
--- a/src/Tesla.NET/Models/IMessageResponse.Generic.cs
+++ b/src/Tesla.NET/Models/IMessageResponse.Generic.cs
@@ -15,6 +15,6 @@ public interface IMessageResponse : IMessageResponse
///
/// Gets the object.
///
- TData Data { get; }
+ TData? Data { get; }
}
}
diff --git a/src/Tesla.NET/Models/IMessageResponse.cs b/src/Tesla.NET/Models/IMessageResponse.cs
index fb14200..9740872 100644
--- a/src/Tesla.NET/Models/IMessageResponse.cs
+++ b/src/Tesla.NET/Models/IMessageResponse.cs
@@ -20,7 +20,7 @@ public interface IMessageResponse
///
/// Gets the raw JSON of the .
///
- JObject RawJson { get; }
+ JObject? RawJson { get; }
///
/// Gets the raw JSON of the .
diff --git a/src/Tesla.NET/Models/IVehicle.cs b/src/Tesla.NET/Models/IVehicle.cs
index 57feb13..c81c9f3 100644
--- a/src/Tesla.NET/Models/IVehicle.cs
+++ b/src/Tesla.NET/Models/IVehicle.cs
@@ -27,25 +27,25 @@ public interface IVehicle
/// Gets the VIN (vehicle identification number) of the .
///
[JsonProperty("vin")]
- string Vin { get; }
+ string? Vin { get; }
///
/// Gets the display name of the .
///
[JsonProperty("display_name")]
- string DisplayName { get; }
+ string? DisplayName { get; }
///
/// Gets the option codes of the .
///
[JsonProperty("option_codes")]
- string OptionCodes { get; }
+ string? OptionCodes { get; }
///
/// Gets the color of the .
///
[JsonProperty("color")]
- string Color { get; }
+ string? Color { get; }
///
/// Gets the tokens of the .
@@ -57,13 +57,13 @@ public interface IVehicle
/// Gets the state of the .
///
[JsonProperty("state")]
- string State { get; }
+ string? State { get; }
///
/// Gets the in service state of the .
///
[JsonProperty("in_service")]
- string InService { get; }
+ string? InService { get; }
///
/// Gets a value indicating whether remote start is enabled for the .
@@ -87,12 +87,12 @@ public interface IVehicle
/// Gets the of the .
///
[JsonProperty("backseat_token")]
- string BackseatToken { get; }
+ string? BackseatToken { get; }
///
/// Gets the of the .
///
[JsonProperty("backseat_token_updated_at")]
- string BackseatTokenUpdatedAt { get; }
+ string? BackseatTokenUpdatedAt { get; }
}
}
diff --git a/src/Tesla.NET/Models/IVehicleState.cs b/src/Tesla.NET/Models/IVehicleState.cs
index 56e2963..ba3139f 100644
--- a/src/Tesla.NET/Models/IVehicleState.cs
+++ b/src/Tesla.NET/Models/IVehicleState.cs
@@ -21,19 +21,19 @@ public interface IVehicleState : IState
/// Gets the state of auto-park.
///
[JsonProperty("autopark_state")]
- string AutoparkState { get; }
+ string? AutoparkState { get; }
///
/// Gets the state of V2 auto-park.
///
[JsonProperty("autopark_state_v2")]
- string AutoparkStateV2 { get; }
+ string? AutoparkStateV2 { get; }
///
/// Gets the style of auto-park.
///
[JsonProperty("autopark_style")]
- string AutoparkStyle { get; }
+ string? AutoparkStyle { get; }
///
/// Gets a value indicating whether the Calendar is supported.
@@ -45,7 +45,7 @@ public interface IVehicleState : IState
/// Gets the car firmware version.
///
[JsonProperty("car_version")]
- string CarVersion { get; }
+ string? CarVersion { get; }
///
/// Gets the state of the center display.
@@ -81,7 +81,7 @@ public interface IVehicleState : IState
/// Gets the last auto-park error.
///
[JsonProperty("last_autopark_error")]
- string LastAutoparkError { get; }
+ string? LastAutoparkError { get; }
///
/// Gets a value indicating whether the car is locked.
@@ -147,7 +147,7 @@ public interface IVehicleState : IState
/// Gets the state of the sunroof.
///
[JsonProperty("sun_roof_state")]
- string SunRoofState { get; }
+ string? SunRoofState { get; }
///
/// Gets a value indicating whether valet mode is enabled.
@@ -165,6 +165,6 @@ public interface IVehicleState : IState
/// Gets the name of the .
///
[JsonProperty("vehicle_name")]
- string VehicleName { get; }
+ string? VehicleName { get; }
}
}
diff --git a/src/Tesla.NET/Models/Internal/ChargeState.cs b/src/Tesla.NET/Models/Internal/ChargeState.cs
index 58bf004..803b063 100644
--- a/src/Tesla.NET/Models/Internal/ChargeState.cs
+++ b/src/Tesla.NET/Models/Internal/ChargeState.cs
@@ -58,9 +58,9 @@ public class ChargeState : IChargeState
/// The .
/// The .
public ChargeState(
- string chargingState = null,
- string fastChargerType = null,
- string fastChargerBrand = null,
+ string? chargingState = null,
+ string? fastChargerType = null,
+ string? fastChargerBrand = null,
long? chargeLimitSoc = null,
long? chargeLimitSocStd = null,
long? chargeLimitSocMin = null,
@@ -84,13 +84,13 @@ public ChargeState(
bool? tripCharging = null,
long? chargeRate = null,
bool? chargePortDoorOpen = null,
- string connChargeCable = null,
+ string? connChargeCable = null,
long? scheduledChargingStartTime = null,
bool? scheduledChargingPending = null,
bool? userChargeEnableRequest = null,
bool? chargeEnableRequest = null,
int? chargerPhases = null,
- string chargePortLatch = null,
+ string? chargePortLatch = null,
long? chargeCurrentRequest = null,
long? chargeCurrentRequestMax = null,
bool? managedChargingActive = null,
@@ -146,17 +146,17 @@ public ChargeState(
///
/// Gets the charging state of a .
///
- public string ChargingState { get; }
+ public string? ChargingState { get; }
///
/// Gets the type of fast charging.
///
- public string FastChargerType { get; }
+ public string? FastChargerType { get; }
///
/// Gets the brand of fast charging.
///
- public string FastChargerBrand { get; }
+ public string? FastChargerBrand { get; }
///
/// Gets the charge limit .
@@ -276,7 +276,7 @@ public ChargeState(
///
/// Gets the type of the charge cable connected to a .
///
- public string ConnChargeCable { get; }
+ public string? ConnChargeCable { get; }
///
/// Gets the schedule charging start time of a .
@@ -311,7 +311,7 @@ public ChargeState(
///
/// Gets the charge port latch of a .
///
- public string ChargePortLatch { get; }
+ public string? ChargePortLatch { get; }
///
/// Gets the charge current request of a .
diff --git a/src/Tesla.NET/Models/Internal/DriveState.cs b/src/Tesla.NET/Models/Internal/DriveState.cs
index 9d8104b..99a0e1f 100644
--- a/src/Tesla.NET/Models/Internal/DriveState.cs
+++ b/src/Tesla.NET/Models/Internal/DriveState.cs
@@ -24,8 +24,8 @@ public class DriveState : IDriveState
/// The .
/// The .
public DriveState(
- string shiftState = null,
- string speed = null,
+ string? shiftState = null,
+ string? speed = null,
long power = 0L,
double latitude = 0D,
double longitude = 0D,
@@ -46,12 +46,12 @@ public DriveState(
///
/// Gets the shift state of a .
///
- public string ShiftState { get; }
+ public string? ShiftState { get; }
///
/// Gets the speed .
///
- public string Speed { get; }
+ public string? Speed { get; }
///
/// Gets the power .
diff --git a/src/Tesla.NET/Models/Internal/MessageResponse.cs b/src/Tesla.NET/Models/Internal/MessageResponse.cs
index 0da1912..d7207ed 100644
--- a/src/Tesla.NET/Models/Internal/MessageResponse.cs
+++ b/src/Tesla.NET/Models/Internal/MessageResponse.cs
@@ -17,7 +17,7 @@ namespace Tesla.NET.Models.Internal
public class MessageResponse : IMessageResponse
where TData : class
{
- private readonly JObject _rawJson;
+ private readonly JObject? _rawJson;
///
/// Initializes a new instance of the class.
@@ -25,7 +25,7 @@ public class MessageResponse : IMessageResponse
/// The .
/// The raw JSON of the .
/// The object.
- public MessageResponse(HttpStatusCode httpStatusCode, JObject rawJson = null, TData data = null)
+ public MessageResponse(HttpStatusCode httpStatusCode, JObject? rawJson = null, TData? data = null)
{
HttpStatusCode = httpStatusCode;
_rawJson = rawJson;
@@ -40,7 +40,7 @@ public MessageResponse(HttpStatusCode httpStatusCode, JObject rawJson = null, TD
///
/// Gets the raw JSON of the .
///
- public JObject RawJson => (JObject)_rawJson?.DeepClone();
+ public JObject? RawJson => (JObject?)_rawJson?.DeepClone();
///
/// Gets the raw JSON of the .
@@ -50,7 +50,7 @@ public MessageResponse(HttpStatusCode httpStatusCode, JObject rawJson = null, TD
///
/// Gets the object.
///
- public TData Data { get; }
+ public TData? Data { get; }
private string DebuggerDisplay => $"{GetType().Name}: {HttpStatusCode:G}";
}
diff --git a/src/Tesla.NET/Models/Internal/Vehicle.cs b/src/Tesla.NET/Models/Internal/Vehicle.cs
index 410828a..cff6858 100644
--- a/src/Tesla.NET/Models/Internal/Vehicle.cs
+++ b/src/Tesla.NET/Models/Internal/Vehicle.cs
@@ -34,18 +34,18 @@ public class Vehicle : IVehicle
public Vehicle(
long id = 0,
long vehicleId = 0,
- string vin = null,
- string displayName = null,
- string optionCodes = null,
- string color = null,
- IReadOnlyCollection tokens = null,
- string state = null,
- string inService = null,
+ string? vin = null,
+ string? displayName = null,
+ string? optionCodes = null,
+ string? color = null,
+ IReadOnlyCollection? tokens = null,
+ string? state = null,
+ string? inService = null,
bool remoteStartEnabled = false,
bool calendarEnabled = false,
bool notificationsEnabled = false,
- string backseatToken = null,
- string backseatTokenUpdatedAt = null)
+ string? backseatToken = null,
+ string? backseatTokenUpdatedAt = null)
{
Id = id;
VehicleId = vehicleId;
@@ -76,22 +76,22 @@ public Vehicle(
///
/// Gets the VIN (vehicle identification number) of the .
///
- public string Vin { get; }
+ public string? Vin { get; }
///
/// Gets the display name of the .
///
- public string DisplayName { get; }
+ public string? DisplayName { get; }
///
/// Gets the option codes of the .
///
- public string OptionCodes { get; }
+ public string? OptionCodes { get; }
///
/// Gets the color of the .
///
- public string Color { get; }
+ public string? Color { get; }
///
/// Gets the tokens of the .
@@ -101,12 +101,12 @@ public Vehicle(
///
/// Gets the state of the .
///
- public string State { get; }
+ public string? State { get; }
///
/// Gets the in service state of the .
///
- public string InService { get; }
+ public string? InService { get; }
///
/// Gets a value indicating whether remote start is enabled for the .
@@ -126,12 +126,12 @@ public Vehicle(
///
/// Gets the of the .
///
- public string BackseatToken { get; }
+ public string? BackseatToken { get; }
///
/// Gets the of the .
///
- public string BackseatTokenUpdatedAt { get; }
+ public string? BackseatTokenUpdatedAt { get; }
private string DebuggerDisplay => $"{GetType().Name}: {DisplayName} VIN={Vin}";
}
diff --git a/src/Tesla.NET/Models/Internal/VehicleState.cs b/src/Tesla.NET/Models/Internal/VehicleState.cs
index 0b89cfc..17885a1 100644
--- a/src/Tesla.NET/Models/Internal/VehicleState.cs
+++ b/src/Tesla.NET/Models/Internal/VehicleState.cs
@@ -44,17 +44,17 @@ public class VehicleState : IVehicleState
/// The .
public VehicleState(
long apiVersion = default,
- string autoparkState = default,
- string autoparkStateV2 = default,
- string autoparkStyle = default,
+ string? autoparkState = default,
+ string? autoparkStateV2 = default,
+ string? autoparkStyle = default,
bool calendarSupported = default,
- string carVersion = default,
+ string? carVersion = default,
long centerDisplayState = default,
long df = default,
long dr = default,
long ft = default,
bool homelinkNearby = default,
- string lastAutoparkError = default,
+ string? lastAutoparkError = default,
bool locked = default,
bool notificationsSupported = default,
double odometer = default,
@@ -65,11 +65,11 @@ public VehicleState(
bool remoteStartSupported = default,
long rt = default,
long? sunRoofPercentOpen = default,
- string sunRoofState = default,
+ string? sunRoofState = default,
long timestamp = default,
bool valetMode = default,
bool valetPinNeeded = default,
- string vehicleName = default)
+ string? vehicleName = default)
{
ApiVersion = apiVersion;
AutoparkState = autoparkState ?? string.Empty;
@@ -108,17 +108,17 @@ public VehicleState(
///
/// Gets the state of auto-park.
///
- public string AutoparkState { get; }
+ public string? AutoparkState { get; }
///
/// Gets the state of V2 auto-park.
///
- public string AutoparkStateV2 { get; }
+ public string? AutoparkStateV2 { get; }
///
/// Gets the style of auto-park.
///
- public string AutoparkStyle { get; }
+ public string? AutoparkStyle { get; }
///
/// Gets a value indicating whether the Calendar is supported.
@@ -128,7 +128,7 @@ public VehicleState(
///
/// Gets the car firmware version.
///
- public string CarVersion { get; }
+ public string? CarVersion { get; }
///
/// Gets the state of the center display.
@@ -158,7 +158,7 @@ public VehicleState(
///
/// Gets the last auto-park error.
///
- public string LastAutoparkError { get; }
+ public string? LastAutoparkError { get; }
///
/// Gets a value indicating whether the car is locked.
@@ -213,7 +213,7 @@ public VehicleState(
///
/// Gets the state of the sunroof.
///
- public string SunRoofState { get; }
+ public string? SunRoofState { get; }
///
/// Gets the millisecond Epoch timestamp when the was captured.
@@ -238,7 +238,7 @@ public VehicleState(
///
/// Gets the name of the .
///
- public string VehicleName { get; }
+ public string? VehicleName { get; }
private string DebuggerDisplay => $"{GetType().Name}: {VehicleName} {CarVersion} @ {TimestampUtc:R}";
}
diff --git a/src/Tesla.NET/Requests/HttpClientExtensions.cs b/src/Tesla.NET/Requests/HttpClientExtensions.cs
index fc0bb28..8d4b14e 100644
--- a/src/Tesla.NET/Requests/HttpClientExtensions.cs
+++ b/src/Tesla.NET/Requests/HttpClientExtensions.cs
@@ -173,7 +173,7 @@ IEnumerable> GetRevokeAccessTokenParameters()
public static Task>>> GetVehiclesAsync(
this HttpClient client,
Uri baseUri,
- string accessToken = null,
+ string? accessToken = null,
CancellationToken cancellationToken = default)
{
if (client == null)
@@ -210,7 +210,7 @@ public static Task>> GetChar
this HttpClient client,
Uri baseUri,
long vehicleId,
- string accessToken = null,
+ string? accessToken = null,
CancellationToken cancellationToken = default)
{
if (client == null)
@@ -247,7 +247,7 @@ public static Task>> GetDrive
this HttpClient client,
Uri baseUri,
long vehicleId,
- string accessToken = null,
+ string? accessToken = null,
CancellationToken cancellationToken = default)
{
if (client == null)
@@ -284,7 +284,7 @@ public static Task>> GetVeh
this HttpClient client,
Uri baseUri,
long vehicleId,
- string accessToken = null,
+ string? accessToken = null,
CancellationToken cancellationToken = default)
{
if (client == null)
@@ -318,7 +318,7 @@ private static async Task PostFormAsync(
this HttpClient client,
Uri requestUri,
IEnumerable> parameters,
- string accessToken = null,
+ string? accessToken = null,
CancellationToken cancellationToken = default)
{
if (client == null)
@@ -362,7 +362,7 @@ private static async Task PostFormAsync(
private static async Task GetWithAuthAsync(
this HttpClient client,
Uri requestUri,
- string accessToken = null,
+ string? accessToken = null,
CancellationToken cancellationToken = default)
{
if (client == null)
@@ -436,7 +436,7 @@ private static async Task> ReadSuccessResponseAsync(
JObject rawJson = await ReadJsonAsync(responseMessage, cancellationToken).ConfigureAwait(false);
JsonSerializer serializer = JsonSerializer.CreateDefault();
- T data = rawJson.ToObject(serializer);
+ T? data = rawJson.ToObject(serializer);
IMessageResponse response = new MessageResponse(responseMessage.StatusCode, rawJson, data);
return response;
@@ -459,7 +459,7 @@ private static async Task> ReadFailureResponseAsync(
if (responseMessage == null)
throw new ArgumentNullException(nameof(responseMessage));
- JObject rawJson = null;
+ JObject? rawJson = null;
try
{
// Check the content is JSON, and the response was not Unauthorized as the API returns a Content-Type
@@ -492,7 +492,7 @@ private static bool IsContentJson(HttpResponseMessage responseMessage)
if (responseMessage == null)
throw new ArgumentNullException(nameof(responseMessage));
- string mediaType = responseMessage.Content?.Headers.ContentType.MediaType;
+ string? mediaType = responseMessage.Content?.Headers.ContentType.MediaType;
return string.Equals(mediaType, "application/json", StringComparison.OrdinalIgnoreCase);
}
diff --git a/src/Tesla.NET/Tesla.NET.csproj b/src/Tesla.NET/Tesla.NET.csproj
index 602cddc..2f70578 100644
--- a/src/Tesla.NET/Tesla.NET.csproj
+++ b/src/Tesla.NET/Tesla.NET.csproj
@@ -5,6 +5,7 @@
latest
true
true
+ enable
..\stylecop.ruleset
false
James Skimming, Patrik Pfaffenbauer
diff --git a/src/Tesla.NET/TeslaClientBase.Disposable.cs b/src/Tesla.NET/TeslaClientBase.Disposable.cs
index 9eabc13..91a6aa9 100644
--- a/src/Tesla.NET/TeslaClientBase.Disposable.cs
+++ b/src/Tesla.NET/TeslaClientBase.Disposable.cs
@@ -37,11 +37,8 @@ protected virtual void Dispose(bool disposing)
{
if (disposing)
{
- Client?.Dispose();
+ Client.Dispose();
}
-
- Client = null;
- BaseUri = null;
}
}
}
diff --git a/src/Tesla.NET/TeslaClientBase.cs b/src/Tesla.NET/TeslaClientBase.cs
index 32ace85..bbf168d 100644
--- a/src/Tesla.NET/TeslaClientBase.cs
+++ b/src/Tesla.NET/TeslaClientBase.cs
@@ -62,12 +62,12 @@ protected TeslaClientBase(Uri baseUri, HttpClient client)
///
/// Gets the base of the Tesla Owner API.
///
- public Uri BaseUri { get; private set; }
+ public Uri BaseUri { get; }
///
/// Gets the underlying HttpClient used to make requests.
///
- public HttpClient Client { get; private set; }
+ public HttpClient Client { get; }
///
/// Transform a collection of s into a chain of
@@ -94,16 +94,15 @@ public static HttpMessageHandler CreatePipeline(IReadOnlyCollection reversedHandlers = handlers.Reverse().Skip(1);
foreach (HttpMessageHandler handler in reversedHandlers)
{
- dHandler = handler as DelegatingHandler;
- if (dHandler == null)
+ if (!(handler is DelegatingHandler next))
{
throw new ArgumentException(
$"All message handlers except the last must be of type '{typeof(DelegatingHandler).Name}'.",
nameof(handlers));
}
- dHandler.InnerHandler = pipeline;
- pipeline = dHandler;
+ next.InnerHandler = pipeline;
+ pipeline = next;
}
return pipeline;
diff --git a/test/Tesla.NET.Tests/Tesla.NET.Tests.csproj b/test/Tesla.NET.Tests/Tesla.NET.Tests.csproj
index 4c96c64..f441b96 100644
--- a/test/Tesla.NET.Tests/Tesla.NET.Tests.csproj
+++ b/test/Tesla.NET.Tests/Tesla.NET.Tests.csproj
@@ -5,6 +5,7 @@
latest
Tesla.NET
false
+ enable
false
From 6f1968da9e251fbdc89b6da386e731318c7c705c Mon Sep 17 00:00:00 2001
From: James Skimming <647706+JSkimming@users.noreply.github.com>
Date: Sun, 1 Mar 2020 11:12:50 +0000
Subject: [PATCH 2/5] Fix nullable test project warnings
---
test/Tesla.NET.Tests/DebuggerDisplayTests.cs | 28 +--
.../FixedContructorArgument.cs | 2 +-
test/Tesla.NET.Tests/GetChargeStateTests.cs | 3 +-
test/Tesla.NET.Tests/GetDriveStateTests.cs | 3 +-
test/Tesla.NET.Tests/GetVehicleStateTests.cs | 8 +-
test/Tesla.NET.Tests/GetVehiclesTests.cs | 3 +-
.../HttpHandlers/ForcedAsyncStream.cs | 1 -
.../HttpHandlers/TestHttpHandler.cs | 94 +++++++--
.../Internal/AccessTokenResponseTests.cs | 30 +--
.../Models/Internal/ChargeStateTests.cs | 180 +++++++++---------
.../Models/Internal/DriveStateTests.cs | 56 +++---
.../Internal/GetChargeStateResponseTests.cs | 6 +-
.../Internal/GetDriveStateResponseTests.cs | 6 +-
.../Internal/GetVehicleStateResponseTests.cs | 7 +-
.../Internal/GetVehiclesResponseTests.cs | 8 +-
.../Models/Internal/MessageResponseTests.cs | 15 +-
.../Models/Internal/VehicleStateTests.cs | 128 +++++++------
.../Models/Internal/VehicleTests.cs | 70 +++----
test/Tesla.NET.Tests/Models/SampleJson.cs | 35 ++--
.../RefreshAccessTokenTests.cs | 10 +-
.../RequestAccessTokenTests.cs | 12 +-
.../Tesla.NET.Tests/RevokeAccessTokenTests.cs | 4 +-
.../TeslaAuthClientInitializationTests.cs | 21 +-
.../TeslaClientInitializationTests.cs | 21 +-
.../TeslaClientMessageHandlerPipelineTests.cs | 4 +-
test/Tesla.NET.Tests/TestContexts.cs | 37 ++--
26 files changed, 431 insertions(+), 361 deletions(-)
diff --git a/test/Tesla.NET.Tests/DebuggerDisplayTests.cs b/test/Tesla.NET.Tests/DebuggerDisplayTests.cs
index 6335c3f..39d3e32 100644
--- a/test/Tesla.NET.Tests/DebuggerDisplayTests.cs
+++ b/test/Tesla.NET.Tests/DebuggerDisplayTests.cs
@@ -12,12 +12,12 @@ namespace Tesla.NET
public abstract class DebuggerDisplayTestsBase : FixtureContext
{
- private Type _sutType;
- private DebuggerDisplayAttribute _debuggerDisplay;
- private PropertyInfo _debuggerDisplayPropertyInfo;
- private MethodInfo _debuggerDisplayGetMethod;
- private object _debuggerDisplayValue;
- protected string DebuggerDisplayText;
+ private Type? _sutType;
+ private DebuggerDisplayAttribute? _debuggerDisplay;
+ private PropertyInfo? _debuggerDisplayPropertyInfo;
+ private MethodInfo? _debuggerDisplayGetMethod;
+ private object? _debuggerDisplayValue;
+ protected string? DebuggerDisplayText;
protected DebuggerDisplayTestsBase(ITestOutputHelper output)
: base(output)
@@ -26,18 +26,18 @@ protected DebuggerDisplayTestsBase(ITestOutputHelper output)
protected void GetDebuggerDisplay(TSut sut)
{
- _sutType = sut.GetType();
+ _sutType = sut?.GetType();
- _debuggerDisplay = _sutType.GetTypeInfo().GetCustomAttribute(inherit: false);
+ _debuggerDisplay = _sutType?.GetCustomAttribute(inherit: false);
_debuggerDisplayPropertyInfo =
- _sutType.GetProperty("DebuggerDisplay", BindingFlags.NonPublic | BindingFlags.Instance);
+ _sutType?.GetProperty("DebuggerDisplay", BindingFlags.NonPublic | BindingFlags.Instance);
- _debuggerDisplayGetMethod = _debuggerDisplayPropertyInfo.GetGetMethod(true);
+ _debuggerDisplayGetMethod = _debuggerDisplayPropertyInfo?.GetGetMethod(true);
- _debuggerDisplayValue = _debuggerDisplayGetMethod.Invoke(sut, new object[] { });
+ _debuggerDisplayValue = _debuggerDisplayGetMethod?.Invoke(sut, new object[] { });
- DebuggerDisplayText = _debuggerDisplayValue.ToString();
+ DebuggerDisplayText = _debuggerDisplayValue?.ToString();
}
[Fact]
@@ -49,6 +49,8 @@ public void have_the_debugger_display_attribute()
[Fact]
public void specify_the_debugger_display_property()
{
+ if (_debuggerDisplay is null) throw new InvalidOperationException(nameof(_debuggerDisplay) + " is null");
+
_debuggerDisplay.Value.Should().BeEquivalentTo("{DebuggerDisplay,nq}");
}
@@ -73,6 +75,8 @@ public void provide_a_string_debugger_display_property()
[Fact]
public void include_the_type_in_the_debugger_display()
{
+ if (_sutType is null) throw new InvalidOperationException(nameof(_sutType) + " is null");
+
DebuggerDisplayText.Should().StartWith($"{_sutType.Name}:");
}
}
diff --git a/test/Tesla.NET.Tests/FixedContructorArgument.cs b/test/Tesla.NET.Tests/FixedContructorArgument.cs
index 6a4e269..02433ea 100644
--- a/test/Tesla.NET.Tests/FixedContructorArgument.cs
+++ b/test/Tesla.NET.Tests/FixedContructorArgument.cs
@@ -41,7 +41,7 @@ public FixedContructorArgument(string parameterName, Func valueF
_valueFunc = valueFunc ?? throw new ArgumentNullException(nameof(valueFunc));
}
- public object Create(object request, ISpecimenContext context)
+ public object? Create(object request, ISpecimenContext context)
{
if (!(request is ParameterInfo pi))
return new NoSpecimen();
diff --git a/test/Tesla.NET.Tests/GetChargeStateTests.cs b/test/Tesla.NET.Tests/GetChargeStateTests.cs
index ece46ef..f3d848a 100644
--- a/test/Tesla.NET.Tests/GetChargeStateTests.cs
+++ b/test/Tesla.NET.Tests/GetChargeStateTests.cs
@@ -160,7 +160,8 @@ public When_getting_the_charge_state_for_a_vehicle_the_raw_JSON(ITestOutputHelpe
// Add random values to test whether it is correctly passed through.
_expected["randomValue1"] = Fixture.Create("randomValue1");
_expected["randomValue2"] = JObject.FromObject(new { fakeId = Guid.NewGuid() });
- _expected["response"]["randomValue3"] = Fixture.Create("randomValue3");
+ JToken response = _expected["response"] ?? throw new InvalidOperationException("response is null.");
+ response["randomValue3"] = Fixture.Create("randomValue3");
Handler.SetResponseContent(_expected);
}
diff --git a/test/Tesla.NET.Tests/GetDriveStateTests.cs b/test/Tesla.NET.Tests/GetDriveStateTests.cs
index 7bd08f1..2d23d0c 100644
--- a/test/Tesla.NET.Tests/GetDriveStateTests.cs
+++ b/test/Tesla.NET.Tests/GetDriveStateTests.cs
@@ -160,7 +160,8 @@ public When_getting_the_drive_state_for_a_vehicle_the_raw_JSON(ITestOutputHelper
// Add random values to test whether it is correctly passed through.
_expected["randomValue1"] = Fixture.Create("randomValue1");
_expected["randomValue2"] = JObject.FromObject(new { fakeId = Guid.NewGuid() });
- _expected["response"]["randomValue3"] = Fixture.Create("randomValue3");
+ JToken response = _expected["response"] ?? throw new InvalidOperationException("response is null.");
+ response["randomValue3"] = Fixture.Create("randomValue3");
Handler.SetResponseContent(_expected);
}
diff --git a/test/Tesla.NET.Tests/GetVehicleStateTests.cs b/test/Tesla.NET.Tests/GetVehicleStateTests.cs
index 41f2364..308fdc1 100644
--- a/test/Tesla.NET.Tests/GetVehicleStateTests.cs
+++ b/test/Tesla.NET.Tests/GetVehicleStateTests.cs
@@ -160,7 +160,8 @@ public When_getting_the_vehicle_state_for_a_vehicle_the_raw_JSON(ITestOutputHelp
// Add random values to test whether it is correctly passed through.
_expected["randomValue1"] = Fixture.Create("randomValue1");
_expected["randomValue2"] = JObject.FromObject(new { fakeId = Guid.NewGuid() });
- _expected["response"]["randomValue3"] = Fixture.Create("randomValue3");
+ JToken response = _expected["response"] ?? throw new InvalidOperationException("response is null.");
+ response["randomValue3"] = Fixture.Create("randomValue3");
Handler.SetResponseContent(_expected);
}
@@ -191,7 +192,8 @@ public When_getting_the_vehicle_state_for_a_vehicle_the_raw_JSON_with_null_value
// Add random values to test whether it is correctly passed through.
_expected["randomValue1"] = Fixture.Create("randomValue1");
_expected["randomValue2"] = JObject.FromObject(new { fakeId = Guid.NewGuid() });
- _expected["response"]["randomValue3"] = Fixture.Create("randomValue3");
+ JToken response = _expected["response"] ?? throw new InvalidOperationException("response is null.");
+ response["randomValue3"] = Fixture.Create("randomValue3");
Handler.SetResponseContent(_expected);
}
@@ -202,6 +204,8 @@ public async Task Should_be_passed_through_in_the_response()
// Act
IMessageResponse> response = await Sut.GetVehicleStateAsync(_vehicleId).ConfigureAwait(false);
+ if (response.Data is null) throw new InvalidOperationException("response data is null.");
+
response.Data.Response.SunRoofPercentOpen.Should().Be(null);
// Assert
diff --git a/test/Tesla.NET.Tests/GetVehiclesTests.cs b/test/Tesla.NET.Tests/GetVehiclesTests.cs
index 6f82238..dcdb8b6 100644
--- a/test/Tesla.NET.Tests/GetVehiclesTests.cs
+++ b/test/Tesla.NET.Tests/GetVehiclesTests.cs
@@ -153,7 +153,8 @@ public When_getting_the_vehicles_for_an_account_the_raw_JSON(ITestOutputHelper o
// Add random values to test whether it is correctly passed through.
_expected["randomValue1"] = Fixture.Create("randomValue1");
_expected["randomValue2"] = JObject.FromObject(new { fakeId = Guid.NewGuid() });
- _expected["response"][0]["randomValue3"] = Fixture.Create("randomValue3");
+ JToken response = _expected["response"]?[0] ?? throw new InvalidOperationException("response is null.");
+ response["randomValue3"] = Fixture.Create("randomValue3");
Handler.SetResponseContent(_expected);
}
diff --git a/test/Tesla.NET.Tests/HttpHandlers/ForcedAsyncStream.cs b/test/Tesla.NET.Tests/HttpHandlers/ForcedAsyncStream.cs
index 4d5776e..610d171 100644
--- a/test/Tesla.NET.Tests/HttpHandlers/ForcedAsyncStream.cs
+++ b/test/Tesla.NET.Tests/HttpHandlers/ForcedAsyncStream.cs
@@ -79,7 +79,6 @@ protected override void Dispose(bool disposing)
_inner?.Dispose();
}
- _inner = null;
base.Dispose(disposing);
}
}
diff --git a/test/Tesla.NET.Tests/HttpHandlers/TestHttpHandler.cs b/test/Tesla.NET.Tests/HttpHandlers/TestHttpHandler.cs
index 4e8995f..6bb188b 100644
--- a/test/Tesla.NET.Tests/HttpHandlers/TestHttpHandler.cs
+++ b/test/Tesla.NET.Tests/HttpHandlers/TestHttpHandler.cs
@@ -17,63 +17,126 @@ namespace Tesla.NET.HttpHandlers
using Newtonsoft.Json.Linq;
using Xunit.Abstractions;
+ ///
+ /// A test that records requests and returned fixed responses.
+ ///
public class TestHttpHandler : HttpMessageHandler
{
private readonly ITestOutputHelper _output;
private int _responseIndex;
+ ///
+ /// Initializes a new instance of the class.
+ ///
+ /// The .
public TestHttpHandler(ITestOutputHelper output)
{
_output = output ?? throw new ArgumentNullException(nameof(output));
}
+ ///
+ /// Gets or sets the last received request.
+ ///
public HttpRequestMessage Request
{
- get => Requests.Count == 0 ? null : Requests[Requests.Count - 1];
+ get
+ {
+ if (Requests.Count == 0)
+ throw new InvalidOperationException("There are no requests to return.");
+
+ return Requests[Requests.Count - 1];
+ }
+
set
{
+ if (value is null)
+ throw new ArgumentNullException(nameof(value));
+
Requests.Clear();
Requests.Add(value);
}
}
+ ///
+ /// Gets the list of received requests.
+ ///
public List Requests { get; } = new List(1);
+ ///
+ /// Gets the list of fixed responses.
+ ///
public List Responses { get; } = new List(1);
- public List RequestContents { get; } = new List(1);
+ ///
+ /// Gets the list of request contents.
+ ///
+ public List RequestContents { get; } = new List(1);
+ ///
+ /// Gets or sets the last fixed response.
+ ///
public HttpResponseMessage Response
{
- get => Responses.Count == 0 ? null : Responses[Responses.Count - 1];
+ get
+ {
+ if (Responses.Count == 0)
+ throw new InvalidOperationException("There are no responses to return.");
+
+ return Responses[Responses.Count - 1];
+ }
+
set
{
+ if (value is null)
+ throw new ArgumentNullException(nameof(value));
+
_responseIndex = 0;
Responses.Clear();
Responses.Add(value);
}
}
- public Func> OnSendingRequest { get; set; }
+ ///
+ /// Get or sets a function to intercept request sending.
+ ///
+ public Func>? OnSendingRequest { get; set; }
+ ///
+ /// Sets the fixed response with the specified .
+ ///
+ /// The response to use.
public void SetResponse(HttpStatusCode code) => SetResponseContent(null, code);
- public void SetResponseContent(object content, HttpStatusCode code = HttpStatusCode.OK)
+ ///
+ /// Sets the fixed response with the specified and .
+ ///
+ /// The response content to use.
+ /// The response to use.
+ public void SetResponseContent(object? content, HttpStatusCode code = HttpStatusCode.OK)
{
Response = CreateResponse(content, code);
}
+ ///
+ /// Adds the fixed response with the specified and .
+ ///
+ /// The response content to use.
+ /// The response to use.
public void AddResponseContent(object content, HttpStatusCode code = HttpStatusCode.OK)
{
Responses.Add(CreateResponse(content, code));
}
+ ///
protected override async Task SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
- string requestContent = await GetStringContent(request.Content).ConfigureAwait(false);
+ if (request is null)
+ throw new ArgumentNullException(nameof(request));
+
+ string? requestContent = await GetStringContent(request.Content).ConfigureAwait(false);
RequestContents.Add(requestContent);
_output.WriteLine($"Started {request.Method} '{request.RequestUri}'");
@@ -97,7 +160,7 @@ protected override async Task SendAsync(
HttpResponseMessage responseMessage =
_responseIndex < Responses.Count
? Responses[_responseIndex++]
- : CreateResponse(string.Empty);
+ : CreateResponse("{}");
responseMessage.RequestMessage = request;
@@ -105,7 +168,7 @@ protected override async Task SendAsync(
$"Completed {request.Method} '{request.RequestUri}' " +
$"with {responseMessage.StatusCode:G} ({responseMessage.StatusCode:D})");
- string responseContent = await GetStringContent(responseMessage.Content).ConfigureAwait(false);
+ string? responseContent = await GetStringContent(responseMessage.Content).ConfigureAwait(false);
if (responseContent != null)
{
_output.WriteLine(responseContent);
@@ -114,15 +177,15 @@ protected override async Task SendAsync(
return responseMessage;
}
- private static async Task GetStringContent(HttpContent content)
+ private static async Task GetStringContent(HttpContent content)
{
- if (content == null)
+ if (content is null)
return null;
string contentData;
if (content is ForcedAsyncStreamContent delayedContent)
{
- using (var s = new StreamReader(delayedContent.Stream, Encoding.UTF8, true, 10240, leaveOpen:true))
+ using (var s = new StreamReader(delayedContent.Stream, Encoding.UTF8, true, 10240, leaveOpen: true))
{
contentData = s.ReadToEnd();
}
@@ -134,7 +197,8 @@ private static async Task GetStringContent(HttpContent content)
contentData = await content.ReadAsStringAsync().ConfigureAwait(false);
}
- bool? isJson = content.Headers?.ContentType?.ToString().Equals("application/json");
+ bool? isJson = content.Headers?.ContentType?.ToString()
+ .Equals("application/json", StringComparison.OrdinalIgnoreCase);
if (isJson.GetValueOrDefault())
{
contentData = JToken.Parse(contentData).ToString(Formatting.Indented);
@@ -143,9 +207,9 @@ private static async Task GetStringContent(HttpContent content)
return contentData;
}
- private static HttpResponseMessage CreateResponse(object content, HttpStatusCode code = HttpStatusCode.OK)
+ private static HttpResponseMessage CreateResponse(object? content, HttpStatusCode code = HttpStatusCode.OK)
{
- if (content == null)
+ if (content is null)
{
return new HttpResponseMessage(code);
}
@@ -166,7 +230,7 @@ private static HttpResponseMessage CreateResponse(object content, HttpStatusCode
Headers =
{
ContentType = new MediaTypeHeaderValue("application/json"),
- }
+ },
};
return new HttpResponseMessage(code)
diff --git a/test/Tesla.NET.Tests/Models/Internal/AccessTokenResponseTests.cs b/test/Tesla.NET.Tests/Models/Internal/AccessTokenResponseTests.cs
index fe93f5a..f62ed05 100644
--- a/test/Tesla.NET.Tests/Models/Internal/AccessTokenResponseTests.cs
+++ b/test/Tesla.NET.Tests/Models/Internal/AccessTokenResponseTests.cs
@@ -30,19 +30,21 @@ public When_serializing_AccessTokenResponse_Should_serialize(ITestOutputHelper o
public void five_properties() => _json.Count.Should().Be(5);
[Fact]
- public void access_token() => _json["access_token"].Value().Should().Be(_sut.AccessToken);
+ public void access_token() => Get("access_token").Value().Should().Be(_sut.AccessToken);
[Fact]
- public void token_type() => _json["token_type"].Value().Should().Be(_sut.TokenType);
+ public void token_type() => Get("token_type").Value().Should().Be(_sut.TokenType);
[Fact]
- public void expires_in() => _json["expires_in"].Value().Should().Be(_sut.ExpiresIn);
+ public void expires_in() => Get("expires_in").Value().Should().Be(_sut.ExpiresIn);
[Fact]
- public void refresh_token() => _json["refresh_token"].Value().Should().Be(_sut.RefreshToken);
+ public void refresh_token() => Get("refresh_token").Value().Should().Be(_sut.RefreshToken);
[Fact]
- public void created_at() => _json["created_at"].Value().Should().Be(_sut.CreatedAt);
+ public void created_at() => Get("created_at").Value().Should().Be(_sut.CreatedAt);
+
+ private JToken Get(string name) => _json[name] ?? throw new InvalidOperationException($"'{name}' is null.");
}
public class When_serializing_and_deserializing_AccessTokenResponse : FixtureContext
@@ -58,7 +60,7 @@ public When_serializing_and_deserializing_AccessTokenResponse(ITestOutputHelper
output.WriteLine("Serialized JSON:" + Environment.NewLine + json);
- _actual = json.ToObject();
+ _actual = json.ToObject() ?? throw new InvalidOperationException();
}
[Fact]
@@ -73,25 +75,27 @@ public class When_deserializing_AccessTokenResponse_Should_deserialize
public When_deserializing_AccessTokenResponse_Should_deserialize(ITestOutputHelper output)
{
_json = SampleJson.AccessTokenResponse;
- _sut = _json.ToObject();
+ _sut = _json.ToObject() ?? throw new InvalidOperationException();
output.WriteLine("Serialized JSON:" + Environment.NewLine + _json);
}
[Fact]
- public void access_token() => _sut.AccessToken.Should().Be(_json["access_token"].Value());
+ public void access_token() => _sut.AccessToken.Should().Be(Get("access_token").Value());
[Fact]
- public void token_type() => _sut.TokenType.Should().Be(_json["token_type"].Value());
+ public void token_type() => _sut.TokenType.Should().Be(Get("token_type").Value());
[Fact]
- public void expires_in() => _sut.ExpiresIn.Should().Be(_json["expires_in"].Value());
+ public void expires_in() => _sut.ExpiresIn.Should().Be(Get("expires_in").Value());
[Fact]
- public void refresh_token() => _sut.RefreshToken.Should().Be(_json["refresh_token"].Value());
+ public void refresh_token() => _sut.RefreshToken.Should().Be(Get("refresh_token").Value());
[Fact]
- public void created_at() => _sut.CreatedAt.Should().Be(_json["created_at"].Value());
+ public void created_at() => _sut.CreatedAt.Should().Be(Get("created_at").Value());
+
+ private JToken Get(string name) => _json[name] ?? throw new InvalidOperationException($"'{name}' is null.");
}
public class When_running_in_the_debugger_AccessTokenResponse_Should : DebuggerDisplayTestsBase
@@ -128,7 +132,7 @@ public class AccessTokenResponse_Should_calculate
public AccessTokenResponse_Should_calculate(ITestOutputHelper output)
{
JObject json = SampleJson.AccessTokenResponse;
- _sut = json.ToObject();
+ _sut = json.ToObject() ?? throw new InvalidOperationException();
output.WriteLine("Serialized JSON:" + Environment.NewLine + json);
}
diff --git a/test/Tesla.NET.Tests/Models/Internal/ChargeStateTests.cs b/test/Tesla.NET.Tests/Models/Internal/ChargeStateTests.cs
index 9a6a781..36c6880 100644
--- a/test/Tesla.NET.Tests/Models/Internal/ChargeStateTests.cs
+++ b/test/Tesla.NET.Tests/Models/Internal/ChargeStateTests.cs
@@ -32,167 +32,169 @@ public When_serializing_ChargeState_Should_serialize(ITestOutputHelper output)
[Fact]
public void charging_state() =>
- _json["charging_state"].Value().Should().Be(_sut.ChargingState);
+ Get("charging_state").Value().Should().Be(_sut.ChargingState);
[Fact]
public void fast_charger_type() =>
- _json["fast_charger_type"].Value().Should().Be(_sut.FastChargerType);
+ Get("fast_charger_type").Value().Should().Be(_sut.FastChargerType);
[Fact]
public void fast_charger_brand() =>
- _json["fast_charger_brand"].Value().Should().Be(_sut.FastChargerBrand);
+ Get("fast_charger_brand").Value().Should().Be(_sut.FastChargerBrand);
[Fact]
public void charge_limit_soc() =>
- _json["charge_limit_soc"].Value().Should().Be(_sut.ChargeLimitSoc);
+ Get("charge_limit_soc").Value().Should().Be(_sut.ChargeLimitSoc);
[Fact]
public void charge_limit_soc_std() =>
- _json["charge_limit_soc_std"].Value().Should().Be(_sut.ChargeLimitSocStd);
+ Get("charge_limit_soc_std").Value().Should().Be(_sut.ChargeLimitSocStd);
[Fact]
public void charge_limit_soc_min() =>
- _json["charge_limit_soc_min"].Value().Should().Be(_sut.ChargeLimitSocMin);
+ Get("charge_limit_soc_min").Value().Should().Be(_sut.ChargeLimitSocMin);
[Fact]
public void charge_limit_soc_max() =>
- _json["charge_limit_soc_max"].Value().Should().Be(_sut.ChargeLimitSocMax);
+ Get("charge_limit_soc_max").Value().Should().Be(_sut.ChargeLimitSocMax);
[Fact]
public void charge_to_max_range() =>
- _json["charge_to_max_range"].Value().Should().Be(_sut.ChargeToMaxRange);
+ Get("charge_to_max_range").Value().Should().Be(_sut.ChargeToMaxRange);
[Fact]
public void max_range_charge_counter() =>
- _json["max_range_charge_counter"].Value().Should().Be(_sut.MaxRangeChargeCounter);
+ Get("max_range_charge_counter").Value().Should().Be(_sut.MaxRangeChargeCounter);
[Fact]
public void fast_charger_present() =>
- _json["fast_charger_present"].Value().Should().Be(_sut.FastChargerPresent);
+ Get("fast_charger_present").Value().Should().Be(_sut.FastChargerPresent);
[Fact]
public void battery_range() =>
- _json["battery_range"].Value().Should().Be(_sut.BatteryRange);
+ Get("battery_range").Value().Should().Be(_sut.BatteryRange);
[Fact]
public void est_battery_range() =>
- _json["est_battery_range"].Value().Should().Be(_sut.EstBatteryRange);
+ Get("est_battery_range").Value().Should().Be(_sut.EstBatteryRange);
[Fact]
public void ideal_battery_range() =>
- _json["ideal_battery_range"].Value().Should().Be(_sut.IdealBatteryRange);
+ Get("ideal_battery_range").Value().Should().Be(_sut.IdealBatteryRange);
[Fact]
public void battery_level() =>
- _json["battery_level"].Value().Should().Be(_sut.BatteryLevel);
+ Get("battery_level").Value().Should().Be(_sut.BatteryLevel);
[Fact]
public void usable_battery_level() =>
- _json["usable_battery_level"].Value().Should().Be(_sut.UsableBatteryLevel);
+ Get("usable_battery_level").Value().Should().Be(_sut.UsableBatteryLevel);
[Fact]
public void charge_energy_added() =>
- _json["charge_energy_added"].Value().Should().Be(_sut.ChargeEnergyAdded);
+ Get("charge_energy_added").Value().Should().Be(_sut.ChargeEnergyAdded);
[Fact]
public void charge_miles_added_rated() =>
- _json["charge_miles_added_rated"].Value().Should().Be(_sut.ChargeMilesAddedRated);
+ Get("charge_miles_added_rated").Value().Should().Be(_sut.ChargeMilesAddedRated);
[Fact]
public void charge_miles_added_ideal() =>
- _json["charge_miles_added_ideal"].Value().Should().Be(_sut.ChargeMilesAddedIdeal);
+ Get("charge_miles_added_ideal").Value().Should().Be(_sut.ChargeMilesAddedIdeal);
[Fact]
public void charger_voltage() =>
- _json["charger_voltage"].Value().Should().Be(_sut.ChargerVoltage);
+ Get("charger_voltage").Value().Should().Be(_sut.ChargerVoltage);
[Fact]
public void charger_pilot_current() =>
- _json["charger_pilot_current"].Value().Should().Be(_sut.ChargerPilotCurrent);
+ Get("charger_pilot_current").Value().Should().Be(_sut.ChargerPilotCurrent);
[Fact]
public void charger_actual_current() =>
- _json["charger_actual_current"].Value().Should().Be(_sut.ChargerActualCurrent);
+ Get("charger_actual_current").Value().Should().Be(_sut.ChargerActualCurrent);
[Fact]
public void charger_power() =>
- _json["charger_power"].Value().Should().Be(_sut.ChargerPower);
+ Get("charger_power").Value().Should().Be(_sut.ChargerPower);
[Fact]
public void time_to_full_charge() =>
- _json["time_to_full_charge"].Value().Should().Be(_sut.TimeToFullCharge);
+ Get("time_to_full_charge").Value().Should().Be(_sut.TimeToFullCharge);
[Fact]
public void trip_charging() =>
- _json["trip_charging"].Value().Should().Be(_sut.TripCharging);
+ Get("trip_charging").Value().Should().Be(_sut.TripCharging);
[Fact]
public void charge_rate() =>
- _json["charge_rate"].Value().Should().Be(_sut.ChargeRate);
+ Get("charge_rate").Value().Should().Be(_sut.ChargeRate);
[Fact]
public void charge_port_door_open() =>
- _json["charge_port_door_open"].Value().Should().Be(_sut.ChargePortDoorOpen);
+ Get("charge_port_door_open").Value().Should().Be(_sut.ChargePortDoorOpen);
[Fact]
public void conn_charge_cable() =>
- _json["conn_charge_cable"].Value().Should().Be(_sut.ConnChargeCable);
+ Get("conn_charge_cable").Value().Should().Be(_sut.ConnChargeCable);
[Fact]
public void scheduled_charging_start_time() =>
- _json["scheduled_charging_start_time"].Value().Should().Be(_sut.ScheduledChargingStartTime);
+ Get("scheduled_charging_start_time").Value().Should().Be(_sut.ScheduledChargingStartTime);
[Fact]
public void scheduled_charging_pending() =>
- _json["scheduled_charging_pending"].Value().Should().Be(_sut.ScheduledChargingPending);
+ Get("scheduled_charging_pending").Value().Should().Be(_sut.ScheduledChargingPending);
[Fact]
public void user_charge_enable_request() =>
- _json["user_charge_enable_request"].Value().Should().Be(_sut.UserChargeEnableRequest);
+ Get("user_charge_enable_request").Value().Should().Be(_sut.UserChargeEnableRequest);
[Fact]
public void charge_enable_request() =>
- _json["charge_enable_request"].Value().Should().Be(_sut.ChargeEnableRequest);
+ Get("charge_enable_request").Value().Should().Be(_sut.ChargeEnableRequest);
[Fact]
public void charger_phases() =>
- _json["charger_phases"].Value().Should().Be(_sut.ChargerPhases);
+ Get("charger_phases").Value().Should().Be(_sut.ChargerPhases);
[Fact]
public void charge_port_latch() =>
- _json["charge_port_latch"].Value().Should().Be(_sut.ChargePortLatch);
+ Get("charge_port_latch").Value().Should().Be(_sut.ChargePortLatch);
[Fact]
public void charge_current_request() =>
- _json["charge_current_request"].Value().Should().Be(_sut.ChargeCurrentRequest);
+ Get("charge_current_request").Value().Should().Be(_sut.ChargeCurrentRequest);
[Fact]
public void charge_current_request_max() =>
- _json["charge_current_request_max"].Value().Should().Be(_sut.ChargeCurrentRequestMax);
+ Get("charge_current_request_max").Value().Should().Be(_sut.ChargeCurrentRequestMax);
[Fact]
public void managed_charging_active() =>
- _json["managed_charging_active"].Value().Should().Be(_sut.ManagedChargingActive);
+ Get("managed_charging_active").Value().Should().Be(_sut.ManagedChargingActive);
[Fact]
public void managed_charging_user_canceled() =>
- _json["managed_charging_user_canceled"].Value().Should().Be(_sut.ManagedChargingUserCanceled);
+ Get("managed_charging_user_canceled").Value().Should().Be(_sut.ManagedChargingUserCanceled);
[Fact]
public void managed_charging_start_time() =>
- _json["managed_charging_start_time"].Value().Should().Be(_sut.ManagedChargingStartTime);
+ Get("managed_charging_start_time").Value().Should().Be(_sut.ManagedChargingStartTime);
[Fact]
public void battery_heater_on() =>
- _json["battery_heater_on"].Value().Should().Be(_sut.BatteryHeaterOn);
+ Get("battery_heater_on").Value().Should().Be(_sut.BatteryHeaterOn);
[Fact]
public void not_enough_power_to_heat() =>
- _json["not_enough_power_to_heat"].Value().Should().Be(_sut.NotEnoughPowerToHeat);
+ Get("not_enough_power_to_heat").Value().Should().Be(_sut.NotEnoughPowerToHeat);
[Fact]
public void timestamp() =>
- _json["timestamp"].Value().Should().Be(_sut.Timestamp);
+ Get("timestamp").Value().Should().Be(_sut.Timestamp);
+
+ private JToken Get(string name) => _json[name] ?? throw new InvalidOperationException($"'{name}' is null.");
}
public class When_serializing_and_deserializing_ChargeState : FixtureContext
@@ -208,7 +210,7 @@ public When_serializing_and_deserializing_ChargeState(ITestOutputHelper output)
output.WriteLine("Serialized JSON:" + Environment.NewLine + json);
- _actual = json.ToObject();
+ _actual = json.ToObject() ?? throw new InvalidOperationException();
}
[Fact]
@@ -224,174 +226,176 @@ public When_deserializing_ChargeState_Should_deserialize(ITestOutputHelper outpu
: base(output)
{
_json = SampleJson.ChargeState;
- _sut = _json.ToObject();
+ _sut = _json.ToObject() ?? throw new InvalidOperationException();
output.WriteLine("Serialized JSON:" + Environment.NewLine + _json);
}
[Fact]
public void charging_state() =>
- _sut.ChargingState.Should().Be(_json["charging_state"].Value());
+ _sut.ChargingState.Should().Be(Get("charging_state").Value());
[Fact]
public void fast_charger_type() =>
- _sut.FastChargerType.Should().Be(_json["fast_charger_type"].Value());
+ _sut.FastChargerType.Should().Be(Get("fast_charger_type").Value());
[Fact]
public void fast_charger_brand() =>
- _sut.FastChargerBrand.Should().Be(_json["fast_charger_brand"].Value());
+ _sut.FastChargerBrand.Should().Be(Get("fast_charger_brand").Value());
[Fact]
public void charge_limit_soc() =>
- _sut.ChargeLimitSoc.Should().Be(_json["charge_limit_soc"].Value());
+ _sut.ChargeLimitSoc.Should().Be(Get("charge_limit_soc").Value());
[Fact]
public void charge_limit_soc_std() =>
- _sut.ChargeLimitSocStd.Should().Be(_json["charge_limit_soc_std"].Value());
+ _sut.ChargeLimitSocStd.Should().Be(Get("charge_limit_soc_std").Value());
[Fact]
public void charge_limit_soc_min() =>
- _sut.ChargeLimitSocMin.Should().Be(_json["charge_limit_soc_min"].Value());
+ _sut.ChargeLimitSocMin.Should().Be(Get("charge_limit_soc_min").Value());
[Fact]
public void charge_limit_soc_max() =>
- _sut.ChargeLimitSocMax.Should().Be(_json["charge_limit_soc_max"].Value());
+ _sut.ChargeLimitSocMax.Should().Be(Get("charge_limit_soc_max").Value());
[Fact]
public void charge_to_max_range() =>
- _sut.ChargeToMaxRange.Should().Be(_json["charge_to_max_range"].Value());
+ _sut.ChargeToMaxRange.Should().Be(Get("charge_to_max_range").Value());
[Fact]
public void max_range_charge_counter() =>
- _sut.MaxRangeChargeCounter.Should().Be(_json["max_range_charge_counter"].Value());
+ _sut.MaxRangeChargeCounter.Should().Be(Get("max_range_charge_counter").Value());
[Fact]
public void fast_charger_present() =>
- _sut.FastChargerPresent.Should().Be(_json["fast_charger_present"].Value());
+ _sut.FastChargerPresent.Should().Be(Get("fast_charger_present").Value());
[Fact]
public void battery_range() =>
- _sut.BatteryRange.Should().Be(_json["battery_range"].Value());
+ _sut.BatteryRange.Should().Be(Get("battery_range").Value());
[Fact]
public void est_battery_range() =>
- _sut.EstBatteryRange.Should().Be(_json["est_battery_range"].Value());
+ _sut.EstBatteryRange.Should().Be(Get("est_battery_range").Value());
[Fact]
public void ideal_battery_range() =>
- _sut.IdealBatteryRange.Should().Be(_json["ideal_battery_range"].Value());
+ _sut.IdealBatteryRange.Should().Be(Get("ideal_battery_range").Value());
[Fact]
public void battery_level() =>
- _sut.BatteryLevel.Should().Be(_json["battery_level"].Value());
+ _sut.BatteryLevel.Should().Be(Get("battery_level").Value());
[Fact]
public void usable_battery_level() =>
- _sut.UsableBatteryLevel.Should().Be(_json["usable_battery_level"].Value());
+ _sut.UsableBatteryLevel.Should().Be(Get("usable_battery_level").Value());
[Fact]
public void charge_energy_added() =>
- _sut.ChargeEnergyAdded.Should().Be(_json["charge_energy_added"].Value());
+ _sut.ChargeEnergyAdded.Should().Be(Get("charge_energy_added").Value());
[Fact]
public void charge_miles_added_rated() =>
- _sut.ChargeMilesAddedRated.Should().Be(_json["charge_miles_added_rated"].Value());
+ _sut.ChargeMilesAddedRated.Should().Be(Get("charge_miles_added_rated").Value());
[Fact]
public void charge_miles_added_ideal() =>
- _sut.ChargeMilesAddedIdeal.Should().Be(_json["charge_miles_added_ideal"].Value());
+ _sut.ChargeMilesAddedIdeal.Should().Be(Get("charge_miles_added_ideal").Value());
[Fact]
public void charger_voltage() =>
- _sut.ChargerVoltage.Should().Be(_json["charger_voltage"].Value());
+ _sut.ChargerVoltage.Should().Be(Get("charger_voltage").Value());
[Fact]
public void charger_pilot_current() =>
- _sut.ChargerPilotCurrent.Should().Be(_json["charger_pilot_current"].Value());
+ _sut.ChargerPilotCurrent.Should().Be(Get("charger_pilot_current").Value());
[Fact]
public void charger_actual_current() =>
- _sut.ChargerActualCurrent.Should().Be(_json["charger_actual_current"].Value());
+ _sut.ChargerActualCurrent.Should().Be(Get("charger_actual_current").Value());
[Fact]
public void charger_power() =>
- _sut.ChargerPower.Should().Be(_json["charger_power"].Value());
+ _sut.ChargerPower.Should().Be(Get("charger_power").Value());
[Fact]
public void time_to_full_charge() =>
- _sut.TimeToFullCharge.Should().Be(_json["time_to_full_charge"].Value());
+ _sut.TimeToFullCharge.Should().Be(Get("time_to_full_charge").Value());
[Fact]
public void trip_charging() =>
- _sut.TripCharging.Should().Be(_json["trip_charging"].Value());
+ _sut.TripCharging.Should().Be(Get("trip_charging").Value());
[Fact]
public void charge_rate() =>
- _sut.ChargeRate.Should().Be(_json["charge_rate"].Value());
+ _sut.ChargeRate.Should().Be(Get("charge_rate").Value());
[Fact]
public void charge_port_door_open() =>
- _sut.ChargePortDoorOpen.Should().Be(_json["charge_port_door_open"].Value());
+ _sut.ChargePortDoorOpen.Should().Be(Get("charge_port_door_open").Value());
[Fact]
public void conn_charge_cable() =>
- _sut.ConnChargeCable.Should().Be(_json["conn_charge_cable"].Value());
+ _sut.ConnChargeCable.Should().Be(Get("conn_charge_cable").Value());
[Fact]
public void scheduled_charging_start_time() =>
- _sut.ScheduledChargingStartTime.Should().Be(_json["scheduled_charging_start_time"].Value());
+ _sut.ScheduledChargingStartTime.Should().Be(Get("scheduled_charging_start_time").Value());
[Fact]
public void scheduled_charging_pending() =>
- _sut.ScheduledChargingPending.Should().Be(_json["scheduled_charging_pending"].Value());
+ _sut.ScheduledChargingPending.Should().Be(Get("scheduled_charging_pending").Value());
[Fact]
public void user_charge_enable_request() =>
- _sut.UserChargeEnableRequest.Should().Be(_json["user_charge_enable_request"].Value());
+ _sut.UserChargeEnableRequest.Should().Be(Get("user_charge_enable_request").Value());
[Fact]
public void charge_enable_request() =>
- _sut.ChargeEnableRequest.Should().Be(_json["charge_enable_request"].Value());
+ _sut.ChargeEnableRequest.Should().Be(Get("charge_enable_request").Value());
[Fact]
public void charger_phases() =>
- _sut.ChargerPhases.Should().Be(_json["charger_phases"].Value());
+ _sut.ChargerPhases.Should().Be(Get("charger_phases").Value());
[Fact]
public void charge_port_latch() =>
- _sut.ChargePortLatch.Should().Be(_json["charge_port_latch"].Value());
+ _sut.ChargePortLatch.Should().Be(Get("charge_port_latch").Value());
[Fact]
public void charge_current_request() =>
- _sut.ChargeCurrentRequest.Should().Be(_json["charge_current_request"].Value());
+ _sut.ChargeCurrentRequest.Should().Be(Get("charge_current_request").Value());
[Fact]
public void charge_current_request_max() =>
- _sut.ChargeCurrentRequestMax.Should().Be(_json["charge_current_request_max"].Value());
+ _sut.ChargeCurrentRequestMax.Should().Be(Get("charge_current_request_max").Value());
[Fact]
public void managed_charging_active() =>
- _sut.ManagedChargingActive.Should().Be(_json["managed_charging_active"].Value());
+ _sut.ManagedChargingActive.Should().Be(Get("managed_charging_active").Value());
[Fact]
public void managed_charging_user_canceled() =>
- _sut.ManagedChargingUserCanceled.Should().Be(_json["managed_charging_user_canceled"].Value());
+ _sut.ManagedChargingUserCanceled.Should().Be(Get("managed_charging_user_canceled").Value());
[Fact]
public void managed_charging_start_time() =>
- _sut.ManagedChargingStartTime.Should().Be(_json["managed_charging_start_time"].Value());
+ _sut.ManagedChargingStartTime.Should().Be(Get("managed_charging_start_time").Value());
[Fact]
public void battery_heater_on() =>
- _sut.BatteryHeaterOn.Should().Be(_json["battery_heater_on"].Value());
+ _sut.BatteryHeaterOn.Should().Be(Get("battery_heater_on").Value());
[Fact]
public void not_enough_power_to_heat() =>
- _sut.NotEnoughPowerToHeat.Should().Be(_json["not_enough_power_to_heat"].Value());
+ _sut.NotEnoughPowerToHeat.Should().Be(Get("not_enough_power_to_heat").Value());
[Fact]
public void timestamp() =>
- _sut.Timestamp.Should().Be(_json["timestamp"].Value());
+ _sut.Timestamp.Should().Be(Get("timestamp").Value());
+
+ private JToken Get(string name) => _json[name] ?? throw new InvalidOperationException($"'{name}' is null.");
}
public class When_deserializing_ChargeState_with_minimal_data_Should_default
@@ -402,7 +406,7 @@ public class When_deserializing_ChargeState_with_minimal_data_Should_default
public When_deserializing_ChargeState_with_minimal_data_Should_default(ITestOutputHelper output)
{
_json = SampleJson.ChargeStateMinimal;
- _sut = _json.ToObject