-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathCodeSaverTests.cs
More file actions
101 lines (88 loc) · 3.1 KB
/
Copy pathCodeSaverTests.cs
File metadata and controls
101 lines (88 loc) · 3.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
namespace Testura.Code.Tests.Saver;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Code.Builders;
using Code.Models.Options;
using Code.Saver;
using Microsoft.CodeAnalysis.CSharp.Formatting;
using NUnit.Framework;
[TestFixture]
public class CodeSaverTests
{
private CodeSaver _coderSaver;
[OneTimeSetUp]
public void SetUp()
{
_coderSaver = new CodeSaver();
}
[Test]
public async Task SaveCodeToFileAsync_WhenSavingCodeAsFile_ShouldSaveCorrectly()
{
var cts = new CancellationTokenSource();
var destFile = PrepareDestinationFile();
var compiledCode = new ClassBuilder("TestClass", "test").Build();
await _coderSaver.SaveCodeToFileAsync(compiledCode, destFile.FullName, cts.Token);
Assert.IsTrue(File.Exists(destFile.FullName));
var code = await File.ReadAllTextAsync(destFile.FullName, cts.Token);
Assert.IsNotNull(code);
Assert.AreEqual(
"namespace test\r\n{\r\n public class TestClass\r\n {\r\n }\r\n}",
code);
FileInfo PrepareDestinationFile()
{
var fi = GetDestinationFile();
if (fi.Exists)
{
fi.Delete();
}
return fi;
}
// Returns a temporary predictable file name which will be saved to the filesystem for testing.
// TODO: Use a filesystem abstraction library to avoid saving to file system.
FileInfo GetDestinationFile()
{
var exampleFileName =
nameof(SaveCodeToFileAsync_WhenSavingCodeAsFile_ShouldSaveCorrectly);
var destinationFile = Path.Combine(
Environment.CurrentDirectory,
"UnitTests",
"Saver",
$"{exampleFileName}.cs");
var fi = new FileInfo(destinationFile);
Directory.CreateDirectory(fi.Directory.FullName);
if (fi.Exists)
{
fi.Delete();
}
return fi;
}
}
[Test]
public void SaveCodeAsString_WhenSavingCodeAsString_ShouldGetString()
{
var code = _coderSaver.SaveCodeAsString(new ClassBuilder("TestClass", "test").Build());
Assert.IsNotNull(code);
Assert.AreEqual(
"namespace test\r\n{\r\n public class TestClass\r\n {\r\n }\r\n}",
code);
}
[Test]
public void SaveCodeAsString_WhenSavingCodeAsStringAndOptions_ShouldGetString()
{
var codeSaver = new CodeSaver(
new List<OptionKeyValue>
{
new(CSharpFormattingOptions.NewLinesForBracesInMethods, false)
});
var code = codeSaver.SaveCodeAsString(
new ClassBuilder("TestClass", "test").WithMethods(new MethodBuilder("MyMethod").Build())
.Build());
Assert.IsNotNull(code);
Assert.AreEqual(
"namespace test\r\n{\r\n public class TestClass\r\n {\r\n void MyMethod() {\r\n }\r\n }\r\n}",
code);
}
}