1+ using System ;
2+ using System . IO ;
3+ using System . Xml . Linq ;
4+ using System . Xml . XPath ;
5+ using static System . Console ;
6+
7+ namespace SpecFlow . NetCore
8+ {
9+ internal class AppConfig
10+ {
11+ #region Ignore the strange indentation; it is like that so the final file looks right.
12+ public const string SpecFlowSectionDefinitionType = "TechTalk.SpecFlow.Configuration.ConfigurationSectionHandler, TechTalk.SpecFlow" ;
13+
14+ public const string SpecFlowSectionDefinition = @" <configSections>
15+ <section name=""specFlow"" type=""" + SpecFlowSectionDefinitionType + @""" />
16+ </configSections>" ;
17+
18+ public const string SpecFlowSectionElement = "unitTestProvider" ;
19+
20+ public const string SpecFlowSection = @" <specFlow>
21+ <" + SpecFlowSectionElement + @" name=""xUnit"" />
22+ </specFlow>" ;
23+ #endregion
24+
25+ public string Path { get ; }
26+
27+ public AppConfig ( string path )
28+ {
29+ Path = path ;
30+ }
31+
32+ public static AppConfig CreateIn ( DirectoryInfo directory )
33+ {
34+ var config = new AppConfig ( System . IO . Path . Combine ( directory . FullName , "app.config" ) ) ;
35+
36+ if ( File . Exists ( config . Path ) )
37+ return config ;
38+
39+ WriteLine ( "Generating app.config." ) ;
40+
41+ // Ignore the strange indentation; it is like that so the final file looks right.
42+ var content = $@ "<?xml version=""1.0"" encoding=""utf-8""?>
43+ <configuration>
44+ { SpecFlowSectionDefinition }
45+ { SpecFlowSection }
46+ </configuration>" ;
47+
48+ WriteLine ( content ) ;
49+ WriteLine ( "Saving: " + config . Path ) ;
50+ File . WriteAllText ( config . Path , content ) ;
51+
52+ return config ;
53+ }
54+
55+ public void Validate ( )
56+ {
57+ WriteLine ( "Validating app.config." ) ;
58+
59+ // I would rather use the ConfigurationBuilder, but as of beta8 it fails to read an element without
60+ // a value, e.g.: <unitTestProvider name="xUnit" />
61+ //var config = new ConfigurationBuilder()
62+ // .AddXmlFile(path)
63+ // .Build();
64+
65+ var file = XDocument . Load ( Path ) ;
66+
67+ var definitionType = file . XPathEvaluate ( "string(/configuration/configSections/section[@name='specFlow']/@type)" ) as string ;
68+
69+ if ( definitionType != SpecFlowSectionDefinitionType )
70+ throw new Exception ( "Couldn't find required SpecFlow section handler in app.config. Example:\n " + SpecFlowSectionDefinition ) ;
71+
72+ var element = file . XPathEvaluate ( "string(/configuration/specFlow/unitTestProvider/@name)" ) as string ;
73+
74+ if ( string . IsNullOrWhiteSpace ( element ) )
75+ throw new Exception ( "Couldn't find required SpecFlow element in app.config. Example:\n " + SpecFlowSection ) ;
76+ }
77+ }
78+ }
0 commit comments