Skip to content

Commit

Permalink
chore: Fix tests for new functionallity
Browse files Browse the repository at this point in the history
  • Loading branch information
svrooij committed Dec 8, 2023
1 parent db8bc65 commit 6c5a5c4
Show file tree
Hide file tree
Showing 7 changed files with 46 additions and 28 deletions.
2 changes: 1 addition & 1 deletion src/Sonos.Base/Music/MusicClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ public async Task<bool> FinishLoginAsync(string linkCode, CancellationToken canc
await options.CredentialStore.SaveAccountAsync(options.ServiceId, fault.Details.NewToken.PrivateKey, fault.Details.NewToken.AuthToken, cancellationToken);
return await ExecuteRequest<TBody, TSoap, TResponse>(action, body, skipKeyAndToken, cancellationToken, true);
}
throw new Exception(fault.Message?.Value ?? $"Sonos error {fault.Code}");
throw new MusicClientException(fault.Message?.Value, fault.Code);
}
catch (Exception ex)
{
Expand Down
15 changes: 15 additions & 0 deletions src/Sonos.Base/Music/MusicClientException.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sonos.Base.Music
{
public class MusicClientException : Exception
{
public MusicClientException(string? message, string faultCode) : base(message) { }
public string FaultCode { get; init; }

}
}
16 changes: 4 additions & 12 deletions src/Sonos.Base/Services/Soap/SoapFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,31 +25,23 @@ internal static class SoapFactory
{
internal static HttpRequestMessage CreateRequest<TPayload>(Uri baseUri, string path, TPayload payload, string? action) where TPayload : class
{
var attr = SonosServiceRequestAttribute.GetSonosServiceRequestAttribute<TPayload>();
SonosServiceRequestAttribute serviceRequestAttribute = SonosServiceRequestAttribute.GetSonosServiceRequestAttribute<TPayload>();
if (action is null)
{
throw new ArgumentException("Could not determine action");
}

#if !DEBUG
var xml = GenerateXmlStream(attr.ServiceName, attr.Action ?? action, payload);
var request = new HttpRequestMessage(HttpMethod.Post, new Uri(baseUri, attr.Path))
var xml = GenerateXmlStream(serviceRequestAttribute.ServiceName, serviceRequestAttribute.Action ?? action, payload);
var request = new HttpRequestMessage(HttpMethod.Post, new Uri(baseUri, serviceRequestAttribute.Path))
{
Content = new StreamContent(xml)
};
#else

var xml = GenerateXml(attr.ServiceName, attr.Action ?? action, payload);
var request = new HttpRequestMessage(HttpMethod.Post, new Uri(baseUri, attr.Path))
{
Content = new StringContent(xml, System.Text.Encoding.UTF8, "text/xml")
};
#endif

// Sonos doesn't like content-type 'text/xml; charset=utf-8'
request.Content.Headers.Remove("content-type");
request.Content.Headers.TryAddWithoutValidation("Content-Type", "text/xml; charset=\"utf-8\"");
request.Headers.TryAddWithoutValidation("soapaction", $"urn:schemas-upnp-org:service:{attr.ServiceName}:1#{attr.Action ?? action}");
request.Headers.TryAddWithoutValidation("soapaction", $"urn:schemas-upnp-org:service:{serviceRequestAttribute.ServiceName}:1#{serviceRequestAttribute.Action ?? action}");
return request;
}

Expand Down
21 changes: 18 additions & 3 deletions src/Sonos.Base/SonosDevice.cs
Original file line number Diff line number Diff line change
Expand Up @@ -177,21 +177,36 @@ public async Task<MusicClient> GetMusicClientAsync(int serviceId, string timeZon
/// <param name="cancellationToken"><see cref="CancellationToken"/></param>
public Task<bool> StopAsync(CancellationToken cancellationToken = default) => Coordinator.AVTransportService.StopAsync(cancellationToken);

public async Task<bool> SwitchToLineIn(CancellationToken cancellationToken = default)
/// <summary>
/// Switch a supported device to the Line-in input.
/// </summary>
/// <param name="cancellationToken"><see cref="CancellationToken"/></param>
/// <remarks>Shortcut to <see cref="AVTransportService.SetAVTransportURIAsync(string, Metadata.Didl?, CancellationToken)"/> with the correct trackUri</remarks>
public async Task<bool> SwitchToLineInAsync(CancellationToken cancellationToken = default)
{
await LoadUuidAsync(cancellationToken);
await AVTransportService.SetAVTransportURIAsync($"x-rincon-stream:{Uuid}", null, cancellationToken);
return await AVTransportService.PlayAsync(cancellationToken);
}

public async Task<bool> SwitchToQueue(CancellationToken cancellationToken = default)
/// <summary>
/// Switch the speaker to play the queue
/// </summary>
/// <param name="cancellationToken"><see cref="CancellationToken"/></param>
/// <remarks>Shortcut to <see cref="AVTransportService.SetAVTransportURIAsync(string, Metadata.Didl?, CancellationToken)"/> with the correct trackUri</remarks>
public async Task<bool> SwitchToQueueAsync(CancellationToken cancellationToken = default)
{
await LoadUuidAsync(cancellationToken);
return await AVTransportService.SetAVTransportURIAsync($"x-rincon-queue:{Uuid}#0", null, cancellationToken);

}

public async Task<bool> SwitchToTv(CancellationToken cancellationToken = default)
/// <summary>
/// Switch a supported device to the digital spdif input.
/// </summary>
/// <param name="cancellationToken"><see cref="CancellationToken"/></param>
/// <remarks>Shortcut to <see cref="AVTransportService.SetAVTransportURIAsync(string, Metadata.Didl?, CancellationToken)"/> with the correct trackUri</remarks>
public async Task<bool> SwitchToTvAsync(CancellationToken cancellationToken = default)
{
await LoadUuidAsync(cancellationToken);
await AVTransportService.SetAVTransportURIAsync($"x-sonos-htastream:{Uuid}:spdif", null, cancellationToken);
Expand Down
4 changes: 1 addition & 3 deletions tests/Sonos.Base.Tests/Music/MusicClientTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -99,9 +99,7 @@ public async Task GetMetadata_PicksUpTokenFromSoapFault()
mockedHandler.MockMusicServiceRequest<GetMetadataRequest>("getMetadata", requestBody: new GetMetadataRequest { Id = metadataId }, responseBody: MusicClientConstants.RefreshTokenError(newKey, newToken), authenticationType: AuthenticationType.AppLink, deviceId: deviceId, key: key, token: token, householdId: householdId, httpStatusCode: System.Net.HttpStatusCode.Unauthorized, packResponse: false);

var musicClient = new MusicClient(MusicClientHelpers.CreateOptions(deviceId: deviceId, authenticationType: AuthenticationType.AppLink, token: token, key: key, householdId: householdId), new HttpClient(mockedHandler.Object));
var result = await musicClient.GetMetadataAsync(new GetMetadataRequest { Id = metadataId });


await Assert.ThrowsAsync<MusicClientException>(() => musicClient.GetMetadataAsync(new GetMetadataRequest { Id = metadataId }));
}

[Fact]
Expand Down
10 changes: 5 additions & 5 deletions tests/Sonos.Base.Tests/Music/SpotifyMusicClientTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ namespace Sonos.Base.Tests.Music
[Startup(typeof(Startup))]
public class SpotifyMusicClientTests
{
//private const string SkipReason = "No real tests";
private const string SkipReason = null;
private const string SkipReason = "No real tests";
//private const string SkipReason = null;
private readonly IConfiguration _configuration;
private readonly MusicClient _musicClient;

Expand All @@ -28,8 +28,8 @@ public SpotifyMusicClientTests(IConfiguration configuration)
serviceId: 9,
AuthenticationType.AppLink,
timezone: "+02:00",
deviceId: _configuration.GetValue<string>("SONOS_DEVICE_ID"),
householdId: _configuration.GetValue<string>("SONOS_HOUSEHOLD_ID"), key: key, token: token));
deviceId: _configuration.GetValue<string>("SONOS_DEVICE_ID") ?? Guid.NewGuid().ToString(),
householdId: _configuration.GetValue<string>("SONOS_HOUSEHOLD_ID") ?? Guid.NewGuid().ToString(), key: key, token: token));


}
Expand All @@ -45,7 +45,7 @@ public async Task MusicClient_LoadsAppLink()
Assert.StartsWith("https://", result.AuthorizeAccount.DeviceLink.RegistrationUrl);
}

[Fact]
[Fact(Skip = SkipReason)]
public async Task MusicClient_LoadsDeviceAuthCode()
{
var linkCode = "ZDZNMD";
Expand Down
6 changes: 2 additions & 4 deletions tests/Sonos.Base.Tests/TestHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -88,11 +88,9 @@ internal static bool VerifySonosRequest(this HttpRequestMessage message, string
bool bodyChecked = false;
if (requestBody != null)
{
var streamContent = message.Content as StringContent;

if (streamContent != null)
if (message.Content != null)
{
var content = streamContent.ReadAsStringAsync().GetAwaiter().GetResult().RemoveXmlIndentation() ;
var content = message.Content.ReadAsStringAsync().GetAwaiter().GetResult().RemoveXmlIndentation() ;
var expectedContent = string.Format(SoapRequestFormat, service, action, requestBody).RemoveXmlIndentation();
#if DEBUG
Assert.Equal(expectedContent, content);
Expand Down

0 comments on commit 6c5a5c4

Please sign in to comment.