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

Feature/implementar teste unitarios & testes sonnar cloud #2

Merged
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
47 changes: 47 additions & 0 deletions .github/workflows/build_and_test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
name: Build and Test
on:
push:
branches:
- main
- develop

permissions:
contents: read

jobs:
build_and_test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3

- name: Cache .NET packages
uses: actions/cache@v3
id: dotnet-cache
with:
path: ~/.nuget/packages
key: dotnet-packages-${{ github.repository }}
restore-keys: dotnet-packages-${{ github.repository }}

- name: Setup .NET
uses: actions/setup-dotnet@v3
if: steps.dotnet-cache.outputs.cache-hit != 'true'
with:
dotnet-version: 7.0.x

- name: Restore dependencies
run: dotnet restore
continue-on-error: false

- name: Build
run: dotnet build -restore
continue-on-error: false

- name: Test
run: dotnet test
continue-on-error: false

trigger_tests_sonarcloud:
needs: build_and_test
name: Test and Analysis Code In Sonar Cloud
uses: alexfariakof/Home_Broker_Chart/.github/workflows/test_analyse_in_Sonar_Cloud.yml@main
secrets: inherit
94 changes: 94 additions & 0 deletions .github/workflows/test_analyse_in_Sonar_Cloud.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
name: Test and Analysis Code In Sonar Cloud
on:
workflow_call:
secrets:
ENV_PAT:
required: true
push:
branches:
- hotfix/*
- feature/*
- bugfix/*

pull_request:
types: [opened, synchronize, reopened]
branches:
- hotfix/*
- feature/*
- bugfix/*

jobs:
test_code_in_sonar:
name: Test and Analysis Code In Sonar Cloud
runs-on: windows-latest
steps:
- name: Set up JDK 17
uses: actions/setup-java@v3
with:
java-version: 17
distribution: 'zulu'

- uses: actions/checkout@v3
with:
fetch-depth: 0

- name: Cache SonarCloud packages
id: cache-sonar
uses: actions/cache@v3
with:
path: ~\sonar\cache
key: ${{ runner.os }}-sonar
restore-keys: ${{ runner.os }}-sonar

- name: Create if not Exist Cache Sonar Packages
if: steps.cache-sonar.outputs.cache-hit != 'true'
shell: powershell
run: |
New-Item -Path ~\sonar\cache -ItemType Directory

- name: Cache SonarCloud scanner
id: cache-sonar-scanner
uses: actions/cache@v3
with:
path: .\.sonar\scanner
key: ${{ runner.os }}-sonar-scanner
restore-keys: ${{ runner.os }}-sonar-scanner


- name: Install SonarCloud scanner
if: steps.cache-sonar-scanner.outputs.cache-hit != 'true'
shell: powershell
run: |
New-Item -Path ./.sonar/scanner -ItemType Directory
dotnet tool update dotnet-sonarscanner --tool-path ./.sonar/scanner

- name: Build and analyze
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
shell: powershell
run: |
./.sonar/scanner/dotnet-sonarscanner begin /k:"alexfariakof_Home_Broker_Chart" /o:"alexfariakof" /d:sonar.token="${{ secrets.SONAR_TOKEN }}" /d:sonar.host.url="https://sonarcloud.io" /d:sonar.cs.opencover.reportsPaths="**/coverage.opencover.xml" /d:sonar.exclusions="HomeBrokerXUnit/**, **/.documents/**, **/Program.cs, **/angularapp/**" /d:sonar.cs.lcov.reportPaths="**/lcov.info"

# Executa Build Restore com Teste e coleta o GUID gerado
dotnet test /p:CollectCoverage=true /p:CoverletOutputFormat=cobertura --collect:"XPlat Code Coverage;Format=opencover"

# Encontra o diretório mais recente na pasta TestResults
$latestDir = Get-ChildItem -Directory -Path .\HomeBrokerXUnit\TestResults | Sort-Object LastWriteTime -Descending | Select-Object -First 1
$sourceDirs = Join-Path -Path (Get-Location) -ChildPath "Business"; Join-Path -Path (Get-Location) -ChildPath "Domain"; Join-Path -Path (Get-Location) -ChildPath "Repository"; Join-Path -Path (Get-Location) -ChildPath "webapi";

# Verifica se encontrou um diretório e, em caso afirmativo, obtém o nome do diretório (GUID)
if ($latestDir -ne $null) {
$guid = $latestDir.Name

# Constrói os caminhos dinamicamente
$baseDirectory = Join-Path -Path (Get-Location) -ChildPath "HomeBrokerXUnit"
$coverageXmlPath = Join-Path -Path (Join-Path -Path $baseDirectory -ChildPath "TestResults") -ChildPath $guid

# Gera o relatório de cobertura usando o GUID capturado

dotnet tool install -g dotnet-reportgenerator-globaltool
reportgenerator -reports:$baseDirectory\coverage.cobertura.xml -targetdir:$coverageXmlPath\coveragereport -reporttypes:"lcov;" -sourcedirs:$sourceDirs
}

./.sonar/scanner/dotnet-sonarscanner end /d:sonar.token="${{ secrets.SONAR_TOKEN }}"
10 changes: 10 additions & 0 deletions Business/Business.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Repository\Repository.csproj" />
</ItemGroup>
</Project>
31 changes: 31 additions & 0 deletions Business/HomeBrokerBusiness.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
using Business.Interfaces;
using Domain.Charts.Agreggates;
using Domain.Charts.ValueObject;
using Repository.Interfaces;

namespace Business;
public class HomeBrokerBusiness : IHomeBrokerBusiness
{
private readonly IHomeBrokerRepository homeBrokerRepository;
private Period _period;
public List<MagazineLuizaHistoryPrice> homeBrokerHistory;

public HomeBrokerBusiness(IHomeBrokerRepository _repo)
{
homeBrokerRepository = _repo;
this._period = new Period(DateTime.Now.AddYears(-1), DateTime.Now);
this.homeBrokerHistory = homeBrokerRepository.GetHistoryData(_period).Result;
}

public List<MagazineLuizaHistoryPrice> GetHistoryData(Period period)
{
this._period = period;
return homeBrokerRepository.GetHistoryData(period).Result;
}
public SMA GetSMA()
{
List<decimal> closeValues = homeBrokerHistory.Select(price => price.Close).ToList();
var sma = new SMA(closeValues);
return sma;
}
}
9 changes: 9 additions & 0 deletions Business/Interfaces/IHomeBrokerBusiness.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
using Domain.Charts.Agreggates;
using Domain.Charts.ValueObject;

namespace Business.Interfaces;
public interface IHomeBrokerBusiness
{
public List<MagazineLuizaHistoryPrice> GetHistoryData(Period period);
public SMA GetSMA();
}
12 changes: 0 additions & 12 deletions Domain/Charts/Agreggates/.gitkepp

This file was deleted.

24 changes: 11 additions & 13 deletions Domain/Charts/Agreggates/MagazineLuizaHistoryPrice.cs
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
using CsvHelper.Configuration.Attributes;

namespace Domain.Charts.Agreggates
namespace Domain.Charts.Agreggates;
public class MagazineLuizaHistoryPrice
{
public class MagazineLuizaHistoryPrice
{
public DateTime Date { get; set; }
public decimal Open { get; set; }
public decimal High { get; set; }
public decimal Low { get; set; }
public decimal Close { get; set; }
[Name("Adj Close")]
public decimal AdjClose { get; set; }
public long Volume { get; set; }
}
}
public DateTime Date { get; set; }
public decimal Open { get; set; }
public decimal High { get; set; }
public decimal Low { get; set; }
public decimal Close { get; set; }
[Name("Adj Close")]
public double AdjClose { get; set; }
public long Volume { get; set; }
}
12 changes: 0 additions & 12 deletions Domain/Charts/ValueObject/.gitkepp

This file was deleted.

5 changes: 5 additions & 0 deletions Domain/Charts/ValueObject/EMA.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
namespace Domain.Charts.ValueObject;
public record EMA
{
public List<decimal> Values { get; set; } = new List<decimal>();
}
15 changes: 15 additions & 0 deletions Domain/Charts/ValueObject/Period.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
namespace Domain.Charts.ValueObject;
public record Period
{
public static implicit operator Period((DateTime start, DateTime end) value) => new Period { StartDate = value.start, EndDate = value.end };
public static implicit operator (DateTime start, DateTime end)(Period period) => (period.StartDate, period.EndDate);
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public int Days => (int)(EndDate - StartDate).TotalDays;
private Period() { }
public Period(DateTime startDate, DateTime endDate)
{
StartDate = startDate;
EndDate = endDate;
}
}
25 changes: 25 additions & 0 deletions Domain/Charts/ValueObject/SMA.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
namespace Domain.Charts.ValueObject;
public record SMA
{
public List<decimal> Values { get; set; } = new List<decimal>();
private SMA() { }
public SMA(List<decimal> historyPriceData)
{
if (historyPriceData == null || historyPriceData.Count == 0)
throw new AggregateException("Não há dados para gerar um SMA");

var count = historyPriceData.Count;

for (int i = 0; i < count; i++)
{
decimal sum = 0;
for (int j = 0; j < 4; j++)
{
if (i + j >= count) break;
sum += historyPriceData[i +j];
}
decimal average = sum / 5;
Values.Add(average);
}
}
}
8 changes: 3 additions & 5 deletions Domain/Domain.csproj
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="CsvHelper" Version="30.0.1" />
<PackageReference Include="NSwag.Annotations" Version="13.20.0" />
</ItemGroup>

</Project>
</Project>
27 changes: 27 additions & 0 deletions HomeBrokerXUnit/.Faker/MagazineLuizaHistoryPriceFaker.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
using Bogus;
using Domain.Charts.Agreggates;

namespace HomeBrokerXUnit.Faker;
public class MagazineLuizaHistoryPriceFaker
{
public static MagazineLuizaHistoryPrice GetNewFaker()
{
return new Faker<MagazineLuizaHistoryPrice>()
.RuleFor(p => p.Date, f => f.Date.Recent())
.RuleFor(p => p.Open, f => f.Finance.Amount(100, 1000))
.RuleFor(p => p.High, f => f.Finance.Amount(100, 1000))
.RuleFor(p => p.Low, f => f.Finance.Amount(100, 1000))
.RuleFor(p => p.Close, f => f.Finance.Amount(100, 1000))
.RuleFor(p => p.AdjClose, f => f.Random.Double(50, 150))
.RuleFor(p => p.Volume, f => f.Random.Long(1000, 10000)).Generate();
}
public static List<MagazineLuizaHistoryPrice> GetListFaker(int count)
{
List<MagazineLuizaHistoryPrice> listFaker = new List<MagazineLuizaHistoryPrice>();

for(int i=0; i <=count; i++)
listFaker.Add(GetNewFaker());

return listFaker;
}
}
1 change: 1 addition & 0 deletions HomeBrokerXUnit/Business/.gitKeep
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

43 changes: 43 additions & 0 deletions HomeBrokerXUnit/Domain/MagazineLuizaHistoryPriceTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
using Domain.Charts.Agreggates;
using HomeBrokerXUnit.Faker;

namespace Domain;

public class MagazineLuizaHistoryPriceTest
{
[Fact]
public void Should_Create_Instance_MagazineLuizaHistoryPrice()
{
// Arrange
var faker = MagazineLuizaHistoryPriceFaker.GetNewFaker();
var date = faker.Date;
var open = faker.Open;
var high = faker.High;
var low = faker.Low;
var close = faker.Close;
var adjClose = faker.AdjClose;
var volume = faker.Volume;

// Act
var historyPrice = new MagazineLuizaHistoryPrice
{
Date = date,
Open = open,
High = high,
Low = low,
Close = close,
AdjClose = adjClose,
Volume = volume
};

// Assert
Assert.NotNull(historyPrice);
Assert.Equal(date, historyPrice.Date);
Assert.Equal(open, historyPrice.Open);
Assert.Equal(high, historyPrice.High);
Assert.Equal(low, historyPrice.Low);
Assert.Equal(close, historyPrice.Close);
Assert.Equal(adjClose, historyPrice.AdjClose);
Assert.Equal(volume, historyPrice.Volume);
}
}
Loading