Skip to content

Commit a296d97

Browse files
authored
Merge pull request #11 from magic5644:fix-some-code-for-simplification
Refactor tests and utility methods to improve readability and consistency
2 parents db5a9cf + 1d39186 commit a296d97

File tree

14 files changed

+103
-96
lines changed

14 files changed

+103
-96
lines changed

CodeLineCounter.Tests/CodeAnalyzerTests.cs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ public void TestAnalyzeSolution()
2020
Assert.NotEmpty(projectTotals);
2121
Assert.NotEqual(0, totalLines);
2222
Assert.NotEqual(0, totalFiles);
23+
Assert.NotNull(duplicationMap);
2324
}
2425

2526
[Fact]
@@ -38,7 +39,7 @@ public void AnalyzeSourceCode_Should_Set_CurrentNamespace()
3839
};
3940

4041
// Act
41-
CodeAnalyzer.AnalyzeSourceCode(projectNamespaceMetrics, file, lines, out string? currentNamespace, out int fileLineCount, out int fileCyclomaticComplexity);
42+
CodeAnalyzer.AnalyzeSourceCode(projectNamespaceMetrics, file, lines, out string? currentNamespace, out _, out _);
4243

4344
// Assert
4445
Assert.Equal("MyNamespace", currentNamespace);
@@ -60,7 +61,7 @@ public void AnalyzeSourceCode_Should_Set_FileLineCount()
6061
};
6162

6263
// Act
63-
CodeAnalyzer.AnalyzeSourceCode(projectNamespaceMetrics, file, lines, out string? currentNamespace, out int fileLineCount, out int fileCyclomaticComplexity);
64+
CodeAnalyzer.AnalyzeSourceCode(projectNamespaceMetrics, file, lines, out _, out int fileLineCount, out _);
6465

6566
// Assert - 3 lines only because comment lines are ignored
6667
Assert.Equal(3, fileLineCount);
@@ -82,7 +83,7 @@ public void AnalyzeSourceCode_Should_Set_FileCyclomaticComplexity()
8283
};
8384

8485
// Act
85-
CodeAnalyzer.AnalyzeSourceCode(projectNamespaceMetrics, file, lines, out string? currentNamespace, out int fileLineCount, out int fileCyclomaticComplexity);
86+
CodeAnalyzer.AnalyzeSourceCode(projectNamespaceMetrics, file, lines, out _, out _, out int fileCyclomaticComplexity);
8687

8788
// Assert
8889
Assert.Equal(1, fileCyclomaticComplexity);

CodeLineCounter.Tests/CoreUtilsTests.cs

Lines changed: 43 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -1,61 +1,62 @@
1+
using CodeLineCounter.Utils;
12

2-
namespace CodeLineCounter.Utils.Tests
3+
namespace CodeLineCounter.Tests
34
{
45
public class CoreUtilsTests
56
{
67
[Fact]
78
public void ParseArguments_Should_Return_Correct_Values()
89
{
910
// Arrange
10-
string[] args = new string[] { "-verbose", "-d", "testDirectory" };
11+
string[] args = ["-verbose", "-d", "testDirectory"];
1112

1213
// Act
13-
var result = CoreUtils.ParseArguments(args);
14+
var (Verbose, DirectoryPath, _) = CoreUtils.ParseArguments(args);
1415

1516
// Assert
16-
Assert.True(result.Verbose);
17-
Assert.Equal("testDirectory", result.DirectoryPath);
17+
Assert.True(Verbose);
18+
Assert.Equal("testDirectory", DirectoryPath);
1819
}
1920

2021
[Fact]
2122
public void ParseArguments_help_Should_Return_Correct_Values()
2223
{
2324
// Arrange
24-
string[] args = new string[] { "-help" };
25+
string[] args = ["-help"];
2526

2627
// Act
27-
var result = CoreUtils.ParseArguments(args);
28+
var (_, _, Help) = CoreUtils.ParseArguments(args);
2829

2930
// Assert
30-
Assert.True(result.Help);
31+
Assert.True(Help);
3132
}
3233

3334
[Fact]
3435
public void ParseArguments_Should_Return_Default_Values_When_No_Arguments_Passed()
3536
{
3637
// Arrange
37-
string[] args = new string[0];
38+
string[] args = [];
3839

3940
// Act
40-
var result = CoreUtils.ParseArguments(args);
41+
var (Verbose, DirectoryPath, _) = CoreUtils.ParseArguments(args);
4142

4243
// Assert
43-
Assert.False(result.Verbose);
44-
Assert.Null(result.DirectoryPath);
44+
Assert.False(Verbose);
45+
Assert.Null(DirectoryPath);
4546
}
4647

4748
[Fact]
4849
public void ParseArguments_Should_Ignore_Invalid_Arguments()
4950
{
5051
// Arrange
51-
string[] args = new string[] { "-invalid", "-d", "testDirectory" };
52+
string[] args = ["-invalid", "-d", "testDirectory"];
5253

5354
// Act
54-
var result = CoreUtils.ParseArguments(args);
55+
var (Verbose, DirectoryPath, _) = CoreUtils.ParseArguments(args);
5556

5657
// Assert
57-
Assert.False(result.Verbose);
58-
Assert.Equal("testDirectory", result.DirectoryPath);
58+
Assert.False(Verbose);
59+
Assert.Equal("testDirectory", DirectoryPath);
5960
}
6061

6162
[Fact]
@@ -96,52 +97,50 @@ public void DisplaySolutions_Should_Write_Solutions_To_Console()
9697

9798
var envNewLine = Environment.NewLine;
9899
// Arrange
99-
List<string> solutionFiles = new List<string>
100-
{
100+
List<string> solutionFiles =
101+
[
101102
"Solution1.sln",
102103
"Solution2.sln",
103104
"Solution3.sln"
104-
};
105+
];
105106

106107
// Redirect console output to a StringWriter
107-
using (StringWriter sw = new StringWriter())
108+
using StringWriter sw = new();
109+
Console.SetOut(sw);
110+
111+
// Act
112+
CoreUtils.DisplaySolutions(solutionFiles);
113+
114+
// Assert
115+
string expectedOutput = $"Available solutions:{envNewLine}";
116+
for (int i = 0; i < solutionFiles.Count; i++)
108117
{
109-
Console.SetOut(sw);
110-
111-
// Act
112-
CoreUtils.DisplaySolutions(solutionFiles);
113-
114-
// Assert
115-
string expectedOutput = $"Available solutions:{envNewLine}";
116-
for (int i = 0; i < solutionFiles.Count; i++)
117-
{
118-
expectedOutput += $"{i + 1}. {solutionFiles[i]}{envNewLine}";
119-
}
120-
Assert.Equal(expectedOutput, sw.ToString());
118+
expectedOutput += $"{i + 1}. {solutionFiles[i]}{envNewLine}";
121119
}
120+
Assert.Equal(expectedOutput, sw.ToString());
122121
}
123122

124123
[Fact]
125124
public void GetFilenamesList_Should_Return_List_Of_Filenames()
126125
{
127126
// Arrange
128-
List<string> solutionFiles = new List<string>
129-
{
127+
List<string> solutionFiles =
128+
[
130129
"Solution1.sln",
131130
"Solution2.sln",
132131
"Solution3.sln"
133-
};
132+
];
134133

135134
// Act
136135
List<string> result = CoreUtils.GetFilenamesList(solutionFiles);
137136

138137
// Assert
139-
List<string> expectedFilenames = new List<string>
140-
{
138+
List<string> expectedFilenames =
139+
[
141140
"Solution1.sln",
142141
"Solution2.sln",
143142
"Solution3.sln"
144-
};
143+
];
145144
Assert.Equal(expectedFilenames, result);
146145
}
147146

@@ -151,25 +150,31 @@ public void CheckSettings_WhenHelpIsTrue_ReturnsFalse()
151150
{
152151
// Arrange
153152
(bool Verbose, string? DirectoryPath, bool Help) settings = (true, null, true);
153+
using var sw = new StringWriter();
154+
Console.SetOut(sw);
154155

155156
// Act
156157
var result = CoreUtils.CheckSettings(settings);
157158

158159
// Assert
159160
Assert.False(result);
161+
Assert.Contains("Usage:", sw.ToString());
160162
}
161163

162164
[Fact]
163165
public void CheckSettings_WhenDirectoryPathIsNull_ReturnsFalse()
164166
{
165167
// Arrange
166168
(bool Verbose, string? DirectoryPath, bool Help) settings = (Verbose: false, DirectoryPath: null, Help: false);
169+
using var sw = new StringWriter();
170+
Console.SetOut(sw);
167171

168172
// Act
169173
var result = CoreUtils.CheckSettings(settings);
170174

171175
// Assert
172176
Assert.False(result);
177+
Assert.Contains("Please provide the directory path", sw.ToString());
173178
}
174179

175180
[Fact]

CodeLineCounter.Tests/CsvExporterTests.cs

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -73,8 +73,8 @@ public void ExportCodeDuplicationsToCsv_ShouldCallSerializeWithCorrectParameters
7373
var filePath = "test4.csv";
7474
var duplications = new List<DuplicationCode>
7575
{
76-
new DuplicationCode { CodeHash = "hash1", FilePath = "file1.cs", MethodName = "method1", StartLine = 10, NbLines = 20 },
77-
new DuplicationCode { CodeHash = "hash2", FilePath = "file2.cs", MethodName = "method2", StartLine = 8, NbLines = 10 }
76+
new() { CodeHash = "hash1", FilePath = "file1.cs", MethodName = "method1", StartLine = 10, NbLines = 20 },
77+
new() { CodeHash = "hash2", FilePath = "file2.cs", MethodName = "method2", StartLine = 8, NbLines = 10 }
7878
};
7979

8080

@@ -91,16 +91,16 @@ public void ExportCodeDuplicationsToCsv_ShouldCallSerializeWithCorrectParameters
9191

9292
}
9393

94-
private List<NamespaceMetrics> GetSampleNamespaceMetrics()
94+
private static List<NamespaceMetrics> GetSampleNamespaceMetrics()
9595
{
96-
return new List<NamespaceMetrics>
97-
{
96+
return
97+
[
9898
new NamespaceMetrics { ProjectName="Project1", ProjectPath = ".", NamespaceName = "Namespace1", FileName = "File1", FilePath = ".", LineCount = 100, CyclomaticComplexity = 0, CodeDuplications = 0 },
9999
new NamespaceMetrics { ProjectName="Project2", ProjectPath = ".", NamespaceName = "Namespace2", FileName = "File2", FilePath = ".", LineCount = 200, CyclomaticComplexity = 5, CodeDuplications = 2 }
100-
};
100+
];
101101
}
102102

103-
private Dictionary<string, int> GetSampleProjectTotals()
103+
private static Dictionary<string, int> GetSampleProjectTotals()
104104
{
105105
return new Dictionary<string, int>
106106
{
@@ -109,13 +109,13 @@ private Dictionary<string, int> GetSampleProjectTotals()
109109
};
110110
}
111111

112-
private List<DuplicationCode> GetSampleDuplicationCodes()
112+
private static List<DuplicationCode> GetSampleDuplicationCodes()
113113
{
114-
return new List<DuplicationCode>
115-
{
114+
return
115+
[
116116
new DuplicationCode { CodeHash = "Code1", FilePath = ".", MethodName = "Method1", StartLine = 10 , NbLines = 20 },
117117
new DuplicationCode { CodeHash = "Code2", FilePath = ".", MethodName = "Method2", StartLine = 15 , NbLines = 25 }
118-
};
118+
];
119119
}
120120
}
121121
}

CodeLineCounter.Tests/CsvHandlerTests.cs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,9 @@
44
using CsvHelper;
55
using System.Linq;
66
using Xunit;
7+
using CodeLineCounter.Utils;
78

8-
namespace CodeLineCounter.Utils.Tests
9+
namespace CodeLineCounter.Tests
910
{
1011
public class CsvHandlerTests
1112
{
@@ -21,8 +22,8 @@ public void Serialize_ValidData_WritesToFile()
2122
// Arrange
2223
var data = new List<TestRecord>
2324
{
24-
new TestRecord { Id = 1, Name = "Alice" },
25-
new TestRecord { Id = 2, Name = "Bob" }
25+
new() { Id = 1, Name = "Alice" },
26+
new() { Id = 2, Name = "Bob" }
2627
};
2728
string filePath = "test_1.csv";
2829

CodeLineCounter.Tests/FileUtilsTests.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1+
using CodeLineCounter.Utils;
12

2-
namespace CodeLineCounter.Utils.Tests
3+
namespace CodeLineCounter.Tests
34
{
45
public class FileUtilsTests
56
{

CodeLineCounter.Tests/HashUtilsTest.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1+
using CodeLineCounter.Utils;
12

2-
namespace CodeLineCounter.Utils.Tests
3+
namespace CodeLineCounter.Tests
34
{
45
public class HashUtilsTests
56
{

CodeLineCounter/Program.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ private static void AnalyzeAndExportSolution(string solutionPath, bool verbose)
6767
Console.WriteLine($"Percentage of duplicated code: {percentageDuplication:F2} %");
6868

6969
Parallel.Invoke(
70-
() => CsvExporter.ExportToCsv(csvFilePath, metrics.ToList(), projectTotals, totalLines, duplicationMap, solutionPath),
70+
() => CsvExporter.ExportToCsv(csvFilePath, metrics, projectTotals, totalLines, duplicationMap, solutionPath),
7171
() => CsvExporter.ExportCodeDuplicationsToCsv(duplicationCsvFilePath, duplicationMap)
7272
);
7373

CodeLineCounter/Services/CodeAnalyzer.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ private static void AnalyzeProject(string solutionDirectory, string projectFile,
3939
string projectName = Path.GetFileNameWithoutExtension(projectFile);
4040
string relativeProjectPath = solutionDirectory != null ? Path.GetRelativePath(solutionDirectory, projectFile) : projectFile;
4141

42-
var files = projectDirectory != null ? FileUtils.GetAllCsFiles(projectDirectory) : new List<string>();
42+
var files = projectDirectory != null ? FileUtils.GetAllCsFiles(projectDirectory) : [];
4343

4444
int projectLineCount = 0;
4545
var projectNamespaceMetrics = new Dictionary<string, int>();

CodeLineCounter/Services/CodeDuplicationChecker.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ public class CodeDuplicationChecker
1818
{
1919
private readonly ConcurrentDictionary<string, HashSet<DuplicationCode>> duplicationMap;
2020
private readonly ConcurrentDictionary<string, HashSet<DuplicationCode>> hashMap;
21-
private readonly object duplicationLock = new object();
21+
private readonly object duplicationLock = new();
2222

2323
public CodeDuplicationChecker()
2424
{
@@ -63,7 +63,7 @@ public void DetectCodeDuplicationInSourceCode(string normalizedPath, string sour
6363
NbLines = nbLines
6464
};
6565

66-
hashMap.AddOrUpdate(hash, new HashSet<DuplicationCode> { duplicationCode },
66+
hashMap.AddOrUpdate(hash, [duplicationCode],
6767
(key, set) =>
6868
{
6969
lock (set)

CodeLineCounter/Utils/CSVHandler.cs

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,24 +6,20 @@
66

77
namespace CodeLineCounter.Utils
88
{
9-
public class CsvHandler
9+
public static class CsvHandler
1010
{
1111
public static void Serialize<T>(IEnumerable<T> data, string filePath)
1212
{
13-
using (var writer = new StreamWriter(filePath))
14-
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
15-
{
16-
csv.WriteRecords(data);
17-
}
13+
using var writer = new StreamWriter(filePath);
14+
using var csv = new CsvWriter(writer, CultureInfo.InvariantCulture);
15+
csv.WriteRecords(data);
1816
}
1917

2018
public static IEnumerable<T> Deserialize<T>(string filePath)
2119
{
22-
using (var reader = new StreamReader(filePath))
23-
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
24-
{
25-
return csv.GetRecords<T>().ToList();
26-
}
20+
using var reader = new StreamReader(filePath);
21+
using var csv = new CsvReader(reader, CultureInfo.InvariantCulture);
22+
return csv.GetRecords<T>().ToList();
2723
}
2824
}
2925

0 commit comments

Comments
 (0)