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

Add initial unit test #24

Merged
merged 6 commits into from
Jun 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion .github/workflows/dotnet.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ on:
branches: [ master ]
pull_request:
branches: [ master ]
workflow_dispatch:

jobs:
build:
Expand All @@ -22,4 +23,22 @@ jobs:
- name: Build
run: dotnet build --no-restore
- name: Test
run: dotnet test --no-build --verbosity normal
run: dotnet test --no-build --verbosity normal --collect:"XPlat Code Coverage" --results-directory ./coverage
- name: Code Coverage Report
uses: irongut/CodeCoverageSummary@v1.3.0
with:
filename: coverage/**/coverage.cobertura.xml
badge: true
fail_below_min: false
format: markdown
hide_branch_rate: false
hide_complexity: true
indicators: true
output: both
thresholds: '60 80'
- name: Add Coverage PR Comment
uses: marocchino/sticky-pull-request-comment@v2
if: github.event_name == 'pull_request'
with:
recreate: true
path: code-coverage-results.md
8 changes: 7 additions & 1 deletion BaseballSharp.sln
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BaseballSharpCli", "samples
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BaseballSharp", "src\BaseballSharp.csproj", "{B188B5BF-0708-4F12-BD6A-3A0664BE9172}"
EndProject
Global
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BaseballSharp.Test", "test\BaseballSharp.Test\BaseballSharp.Test.csproj", "{DB0661A1-F7C0-4D43-8BE3-DF66BF9FAF4A}"
EndProject
Global5206EC59-0954-4355-B48B-B014E0E79032
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
Expand All @@ -29,6 +31,10 @@ Global
{B188B5BF-0708-4F12-BD6A-3A0664BE9172}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B188B5BF-0708-4F12-BD6A-3A0664BE9172}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B188B5BF-0708-4F12-BD6A-3A0664BE9172}.Release|Any CPU.Build.0 = Release|Any CPU
{DB0661A1-F7C0-4D43-8BE3-DF66BF9FAF4A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{DB0661A1-F7C0-4D43-8BE3-DF66BF9FAF4A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DB0661A1-F7C0-4D43-8BE3-DF66BF9FAF4A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DB0661A1-F7C0-4D43-8BE3-DF66BF9FAF4A}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
17 changes: 15 additions & 2 deletions src/MLBClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,21 +8,32 @@
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Text.Json;
using System.Threading.Tasks;
using Team = BaseballSharp.DTO.Teams.Team;

[assembly: InternalsVisibleTo("BaseballSharp.Test")]

namespace BaseballSharp
{
/// <summary>
/// The MLBClient class holds all MLB Stats API endpoints that can be accessed from Baseball Sharp.
/// </summary>
public class MLBClient : IMLBClient
{
private static HttpClient _httpClient = new HttpClient();
private HttpClient _httpClient = new HttpClient();
private static readonly string _baseUrl = "https://statsapi.mlb.com/api/v1";
private static readonly short _outsInCompletedInning = 3;

internal HttpClient HttpClient
{
set
{
_httpClient = value;
}
}

private async Task<string> GetResponseAsync(string endpoint)
{

Expand Down Expand Up @@ -52,6 +63,7 @@ public async Task<IEnumerable<Schedule>> GetScheduleAsync(DateTime date)
gameID = game.gamePk,
AwayTeam = game.teams?.away?.team?.name,
HomeTeam = game.teams?.home?.team?.name,
Ballpark = game.venue?.name,
ScheduledInnings = game.scheduledInnings,
StatusCode = Schedule.GetStatusCode(game.status?.statusCode)
});
Expand Down Expand Up @@ -111,7 +123,8 @@ public async Task<IEnumerable<PitchingReport>> GetPitchingReportsAsync(DateTime
{
teamsList.Add(new Models.Team()
{
Name = team.name,
FullName = team.name,
Name = team.teamName,
Location = team.locationName,
Id = team.id,
LeagueId = team.league?.id,
Expand Down
36 changes: 36 additions & 0 deletions test/BaseballSharp.Test/BaseballSharp.Test.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.6.0" />
<PackageReference Include="Moq" Version="4.20.70" />
<PackageReference Include="xunit" Version="2.4.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="6.0.0">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<ProjectReference Include="..\..\src\BaseballSharp.csproj" />
<None Update="Schedule.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="PitchingReports.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="TeamData.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>

</Project>
1 change: 1 addition & 0 deletions test/BaseballSharp.Test/GlobalUsings.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
global using Xunit;
94 changes: 94 additions & 0 deletions test/BaseballSharp.Test/MLBClientShould.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@

using System.Net;
using Moq;
using Moq.Protected;

namespace BaseballSharp.Test
{
public class MLBClientShould
{
private HttpClient BuildMockedHttpClient(string returnContent)
{
var handlerMock = new Mock<HttpMessageHandler>(MockBehavior.Strict);

handlerMock
.Protected()
// Setup the PROTECTED method to mock
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.IsAny<HttpRequestMessage>(),
ItExpr.IsAny<CancellationToken>()
)
// Prepare the expected response of the mocked HttpClient
.ReturnsAsync(new HttpResponseMessage()
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent(returnContent),
})
.Verifiable();

return new HttpClient(handlerMock.Object);
}

[Fact]
public async void ReturnAScheduleGivenAValidDate()
{
var sut = new MLBClient
{
HttpClient = BuildMockedHttpClient(File.ReadAllText("Schedule.json")),
};

var game = (await sut.GetScheduleAsync(DateTime.Now)).ToList().Single();

Assert.Equal("Toronto Blue Jays", game.AwayTeam);
Assert.Equal("Comerica Park", game.Ballpark);
Assert.Equal(746470, game.gameID);
Assert.Equal("Detroit Tigers", game.HomeTeam);
Assert.Equal(9, game.ScheduledInnings);
Assert.Equal(Enums.GameStatus.PreGame, game.StatusCode);
}

[Fact]
public async void ReturnAValidPitchingReportGivenAValidDate()
{
var sut = new MLBClient
{
HttpClient = BuildMockedHttpClient(File.ReadAllText("PitchingReports.json")),
};

var pitchingReport = (await sut.GetPitchingReportsAsync(DateTime.Now)).ToList().Single();

Assert.Equal(607192, pitchingReport.AwayProbablePitcherId);
Assert.Equal("Tyler Glasnow", pitchingReport.AwayProbablePitcherName);
Assert.Equal("", pitchingReport.AwayProbablePitcherNotes);
Assert.Equal("Los Angeles Dodgers", pitchingReport.AwayTeam);
Assert.Equal(656731, pitchingReport.HomeProbablePitcherId);
Assert.Equal("Tylor Megill", pitchingReport.HomeProbablePitcherName);
Assert.Equal("", pitchingReport.HomeProbablePitcherNotes);
Assert.Equal("New York Mets", pitchingReport.HomeTeam);
}

[Fact]
public async void ReturnValidTeamData()
{
var sut = new MLBClient
{
HttpClient = BuildMockedHttpClient(File.ReadAllText("TeamData.json")),
};

var teamData = (await sut.GetTeamDataAsync()).ToList().Single();

Assert.Equal("OAK", teamData.Abbreviation);
Assert.Equal(200, teamData.DivisionId);
Assert.Equal("American League West", teamData.DivisionName);
Assert.Equal("Oakland Athletics", teamData.FullName);
Assert.Equal(133, teamData.Id);
Assert.Equal(103, teamData.LeagueId);
Assert.Equal("American League", teamData.LeagueName);
Assert.Equal("Oakland", teamData.Location);
Assert.Equal("Athletics", teamData.Name);
Assert.Equal(10, teamData.VenueId);
Assert.Equal("Oakland Coliseum", teamData.VenueName);
}
}
}
38 changes: 38 additions & 0 deletions test/BaseballSharp.Test/PitchingReports.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
{
"dates": [
{
"date": "2024-05-28",
"games": [
{
"gamePk": 745818,
"gameDate": "2024-05-28T20:10:00Z",
"status": {
"abstractGameState": "Final"
},
"teams": {
"away": {
"team": {
"id": 119,
"name": "Los Angeles Dodgers"
},
"probablePitcher": {
"id": 607192,
"fullName": "Tyler Glasnow"
}
},
"home": {
"team": {
"id": 121,
"name": "New York Mets"
},
"probablePitcher": {
"id": 656731,
"fullName": "Tylor Megill"
}
}
}
}
]
}
]
}
93 changes: 93 additions & 0 deletions test/BaseballSharp.Test/Schedule.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
{
"copyright": "Copyright 2024 MLB Advanced Media, L.P. Use of any content on this page acknowledges agreement to the terms posted here http://gdx.mlb.com/components/copyright.txt",
"totalItems": 15,
"totalEvents": 0,
"totalGames": 15,
"totalGamesInProgress": 0,
"dates": [
{
"date": "2024-05-25",
"totalItems": 15,
"totalEvents": 0,
"totalGames": 15,
"totalGamesInProgress": 0,
"games": [
{
"gamePk": 746470,
"gameGuid": "02f1258c-fe62-41ae-ab53-374dec7bca3d",
"link": "/api/v1.1/game/746470/feed/live",
"gameType": "R",
"season": "2024",
"gameDate": "2024-05-25T17:10:00Z",
"officialDate": "2024-05-25",
"status": {
"abstractGameState": "Preview",
"codedGameState": "P",
"detailedState": "Pre-Game",
"statusCode": "P",
"startTimeTBD": false,
"abstractGameCode": "P"
},
"teams": {
"away": {
"leagueRecord": {
"wins": 23,
"losses": 27,
"pct": ".460"
},
"score": 0,
"team": {
"id": 141,
"name": "Toronto Blue Jays",
"link": "/api/v1/teams/141"
},
"splitSquad": false,
"seriesNumber": 17
},
"home": {
"leagueRecord": {
"wins": 24,
"losses": 27,
"pct": ".471"
},
"score": 0,
"team": {
"id": 116,
"name": "Detroit Tigers",
"link": "/api/v1/teams/116"
},
"splitSquad": false,
"seriesNumber": 17
}
},
"venue": {
"id": 2394,
"name": "Comerica Park",
"link": "/api/v1/venues/2394"
},
"content": {
"link": "/api/v1/game/746470/content"
},
"gameNumber": 1,
"publicFacing": true,
"doubleHeader": "N",
"gamedayType": "P",
"tiebreaker": "N",
"calendarEventID": "14-746470-2024-05-25",
"seasonDisplay": "2024",
"dayNight": "day",
"scheduledInnings": 9,
"reverseHomeAwayStatus": false,
"inningBreakLength": 120,
"gamesInSeries": 4,
"seriesGameNumber": 3,
"seriesDescription": "Regular Season",
"recordSource": "S",
"ifNecessary": "N",
"ifNecessaryDescription": "Normal Game"
}
],
"events": []
}
]
}
Loading
Loading