2 // System.Configuration.ConfigurationManagerTest.cs - Unit tests
3 // for System.Configuration.ConfigurationManager.
6 // Chris Toshok <toshok@ximian.com>
7 // Atsushi Enomoto <atsushi@ximian.com>
9 // Copyright (C) 2005-2006 Novell, Inc (http://www.novell.com)
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32 using System.Collections;
33 using System.Collections.Specialized;
34 using System.Configuration;
35 using System.Net.Configuration;
37 using NUnit.Framework;
38 using SysConfig = System.Configuration.Configuration;
39 using System.Runtime.InteropServices;
40 using System.Reflection;
42 namespace MonoTests.System.Configuration {
46 public class ConfigurationManagerTest
48 private string originalCurrentDir;
49 private string tempFolder;
54 originalCurrentDir = Directory.GetCurrentDirectory ();
55 tempFolder = Path.Combine (Path.GetTempPath (), this.GetType ().FullName);
56 if (!Directory.Exists (tempFolder))
57 Directory.CreateDirectory (tempFolder);
61 public void TearDown ()
63 Directory.SetCurrentDirectory (originalCurrentDir);
64 if (Directory.Exists (tempFolder))
65 Directory.Delete (tempFolder, true);
68 [Test] // OpenExeConfiguration (ConfigurationUserLevel)
69 [Category ("NotWorking")] // bug #323622
70 public void OpenExeConfiguration1_Remote ()
72 AppDomain domain = null;
74 string config_xml = @"
77 <add key='anyKey' value='42' />
81 config_file = Path.Combine (tempFolder, "otherConfig.noconfigext");
82 File.WriteAllText (config_file, config_xml);
85 AppDomainSetup setup = new AppDomainSetup();
86 setup.ConfigurationFile = config_file;
87 setup.ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
88 domain = AppDomain.CreateDomain("foo", null, setup);
90 RemoteConfig config = RemoteConfig.GetInstance (domain);
92 ConfigurationUserLevel userLevel = ConfigurationUserLevel.None;
93 Assert.AreEqual (config_file, config.GetFilePath (userLevel));
94 Assert.AreEqual ("42", config.GetSettingValue (userLevel, "anyKey"));
95 Assert.AreEqual ("42", config.GetSettingValue ("anyKey"));
98 AppDomain.Unload (domain);
99 File.Delete (config_file);
102 config_file = Path.Combine (tempFolder, "otherConfig.exe.config");
103 File.WriteAllText (config_file, config_xml);
106 AppDomainSetup setup = new AppDomainSetup();
107 setup.ConfigurationFile = config_file;
108 setup.ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
109 domain = AppDomain.CreateDomain("foo", null, setup);
111 RemoteConfig config = RemoteConfig.GetInstance (domain);
113 ConfigurationUserLevel userLevel = ConfigurationUserLevel.None;
114 Assert.AreEqual (config_file, config.GetFilePath (userLevel));
115 Assert.AreEqual ("42", config.GetSettingValue (userLevel, "anyKey"));
116 Assert.AreEqual ("42", config.GetSettingValue ("anyKey"));
119 AppDomain.Unload (domain);
120 File.Delete (config_file);
124 AppDomainSetup setup = new AppDomainSetup();
125 setup.ConfigurationFile = config_file;
126 setup.ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
127 domain = AppDomain.CreateDomain("foo", null, setup);
129 RemoteConfig config = RemoteConfig.GetInstance (domain);
131 ConfigurationUserLevel userLevel = ConfigurationUserLevel.None;
132 Assert.AreEqual (config_file, config.GetFilePath (userLevel));
133 Assert.IsNull (config.GetSettingValue (userLevel, "anyKey"));
134 Assert.IsNull (config.GetSettingValue ("anyKey"));
137 AppDomain.Unload (domain);
138 File.Delete (config_file);
142 [Test] // OpenExeConfiguration (ConfigurationUserLevel)
143 public void OpenExeConfiguration1_UserLevel_None ()
145 SysConfig config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
147 Console.WriteLine("application config path: {0}", config.FilePath);
148 FileInfo fi = new FileInfo (config.FilePath);
149 Assert.AreEqual (TestUtil.ThisConfigFileName, fi.Name);
153 public void OpenExeConfiguration1_UserLevel_PerUserRoaming ()
155 SysConfig config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoaming);
156 Console.WriteLine("roaming user config path: {0}", config.FilePath);
158 FileInfo fi = new FileInfo (config.FilePath);
159 Assert.AreEqual ("user.config", fi.Name);
163 public void OpenExeConfiguration1_UserLevel_PerUserRoamingAndLocal ()
165 SysConfig config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
166 Console.WriteLine("local user config path: {0}", config.FilePath);
168 FileInfo fi = new FileInfo (config.FilePath);
169 Assert.AreEqual ("user.config", fi.Name);
172 [Test] // OpenExeConfiguration (String)
173 public void OpenExeConfiguration2 ()
178 exePath = Path.Combine (tempFolder, "DoesNotExist.whatever");
179 File.Create (exePath).Close ();
181 config = ConfigurationManager.OpenExeConfiguration (exePath);
182 Assert.AreEqual (exePath + ".config", config.FilePath, "#1");
184 exePath = Path.Combine (tempFolder, "SomeExecutable.exe");
185 File.Create (exePath).Close ();
187 config = ConfigurationManager.OpenExeConfiguration (exePath);
188 Assert.AreEqual (exePath + ".config", config.FilePath, "#2");
190 exePath = Path.Combine (tempFolder, "Foo.exe.config");
191 File.Create (exePath).Close ();
193 config = ConfigurationManager.OpenExeConfiguration (exePath);
194 Assert.AreEqual (exePath + ".config", config.FilePath, "#3");
196 Directory.SetCurrentDirectory (tempFolder);
198 exePath = "relative.exe";
199 File.Create (Path.Combine (tempFolder, exePath)).Close ();
202 // The temp directory as computed by the runtime is slightly different, as
203 // it will contain the full path after following links, while the test
204 // below is not comprehensive enough to follow links if there are any
205 // present in tempFolder
208 //config = ConfigurationManager.OpenExeConfiguration (exePath);
209 //Assert.AreEqual (Path.Combine (tempFolder, exePath + ".config"), config.FilePath, "#4");
212 [Test] // OpenExeConfiguration (String)
213 public void OpenExeConfiguration2_ExePath_Empty ()
215 AppDomain domain = AppDomain.CurrentDomain;
217 SysConfig config = ConfigurationManager.OpenExeConfiguration (string.Empty);
218 Assert.AreEqual (domain.SetupInformation.ConfigurationFile, config.FilePath);
221 [Test] // OpenExeConfiguration (String)
222 public void OpenExeConfiguration2_ExePath_Null ()
224 AppDomain domain = AppDomain.CurrentDomain;
226 SysConfig config = ConfigurationManager.OpenExeConfiguration (string.Empty);
227 Assert.AreEqual (domain.SetupInformation.ConfigurationFile, config.FilePath);
230 [Test] // OpenExeConfiguration (String)
231 public void OpenExeConfiguration2_ExePath_DoesNotExist ()
233 String exePath = Path.Combine (tempFolder, "DoesNotExist.exe");
236 ConfigurationManager.OpenExeConfiguration (exePath);
238 } catch (ConfigurationErrorsException ex) {
239 // An error occurred loading a configuration file:
240 // The parameter 'exePath' is invalid
241 Assert.AreEqual (typeof (ConfigurationErrorsException), ex.GetType (), "#2");
242 Assert.IsNull (ex.Filename, "#3");
243 Assert.IsNotNull (ex.InnerException, "#4");
244 Assert.AreEqual (0, ex.Line, "#5");
245 Assert.IsNotNull (ex.Message, "#6");
247 // The parameter 'exePath' is invalid
248 ArgumentException inner = ex.InnerException as ArgumentException;
249 Assert.IsNotNull (inner, "#7");
250 Assert.AreEqual (typeof (ArgumentException), inner.GetType (), "#8");
251 Assert.IsNull (inner.InnerException, "#9");
252 Assert.IsNotNull (inner.Message, "#10");
253 Assert.AreEqual ("exePath", inner.ParamName, "#11");
258 public void exePath_UserLevelNone ()
260 string name = TestUtil.ThisApplicationPath;
261 SysConfig config = ConfigurationManager.OpenExeConfiguration (name);
262 Assert.AreEqual (TestUtil.ThisApplicationPath + ".config", config.FilePath);
266 public void exePath_UserLevelPerRoaming ()
268 SysConfig config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoaming);
269 string filePath = config.FilePath;
270 string applicationData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
271 Assert.IsTrue (filePath.StartsWith (applicationData), "#1:" + filePath);
272 Assert.AreEqual ("user.config", Path.GetFileName (filePath), "#2:" + filePath);
276 public void exePath_UserLevelPerRoamingAndLocal ()
278 SysConfig config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
279 string filePath = config.FilePath;
280 string applicationData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
281 Assert.IsTrue (filePath.StartsWith (applicationData), "#1:" + filePath);
282 Assert.AreEqual ("user.config", Path.GetFileName (filePath), "#2:" + filePath);
286 public void mapped_UserLevelNone ()
288 ExeConfigurationFileMap map = new ExeConfigurationFileMap ();
289 map.ExeConfigFilename = "execonfig";
291 SysConfig config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
292 Console.WriteLine("mapped application config path: {0}", config.FilePath);
294 FileInfo fi = new FileInfo (config.FilePath);
295 Assert.AreEqual ("execonfig", fi.Name);
300 public void mapped_UserLevelPerRoaming ()
302 ExeConfigurationFileMap map = new ExeConfigurationFileMap ();
303 map.ExeConfigFilename = "execonfig";
304 map.RoamingUserConfigFilename = "roaminguser";
306 SysConfig config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.PerUserRoaming);
307 Console.WriteLine("mapped roaming user config path: {0}", config.FilePath);
309 FileInfo fi = new FileInfo (config.FilePath);
310 Assert.AreEqual ("roaminguser", fi.Name);
314 [ExpectedException (typeof (ArgumentException))]
315 [Category ("NotWorking")]
316 public void mapped_UserLevelPerRoaming_no_execonfig ()
318 ExeConfigurationFileMap map = new ExeConfigurationFileMap ();
319 map.RoamingUserConfigFilename = "roaminguser";
321 ConfigurationManager.OpenMappedExeConfiguration (map, ConfigurationUserLevel.PerUserRoaming);
325 public void mapped_UserLevelPerRoamingAndLocal ()
327 ExeConfigurationFileMap map = new ExeConfigurationFileMap ();
328 map.ExeConfigFilename = "execonfig";
329 map.RoamingUserConfigFilename = "roaminguser";
330 map.LocalUserConfigFilename = "localuser";
332 SysConfig config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.PerUserRoamingAndLocal);
333 Console.WriteLine("mapped local user config path: {0}", config.FilePath);
335 FileInfo fi = new FileInfo (config.FilePath);
336 Assert.AreEqual ("localuser", fi.Name);
340 [ExpectedException (typeof (ArgumentException))]
341 [Category ("NotWorking")]
342 public void mapped_UserLevelPerRoamingAndLocal_no_execonfig ()
344 ExeConfigurationFileMap map = new ExeConfigurationFileMap ();
345 map.RoamingUserConfigFilename = "roaminguser";
346 map.LocalUserConfigFilename = "localuser";
348 ConfigurationManager.OpenMappedExeConfiguration (map, ConfigurationUserLevel.PerUserRoamingAndLocal);
352 [ExpectedException (typeof (ArgumentException))]
353 [Category ("NotWorking")]
354 public void mapped_UserLevelPerRoamingAndLocal_no_roaminguser ()
356 ExeConfigurationFileMap map = new ExeConfigurationFileMap ();
357 map.ExeConfigFilename = "execonfig";
358 map.LocalUserConfigFilename = "localuser";
360 ConfigurationManager.OpenMappedExeConfiguration (map, ConfigurationUserLevel.PerUserRoamingAndLocal);
364 public void MachineConfig ()
366 SysConfig config = ConfigurationManager.OpenMachineConfiguration ();
367 Console.WriteLine("machine config path: {0}", config.FilePath);
369 FileInfo fi = new FileInfo (config.FilePath);
370 Assert.AreEqual ("machine.config", fi.Name);
374 public void mapped_MachineConfig ()
376 ConfigurationFileMap map = new ConfigurationFileMap ();
377 map.MachineConfigFilename = "machineconfig";
379 SysConfig config = ConfigurationManager.OpenMappedMachineConfiguration (map);
380 Console.WriteLine("mapped machine config path: {0}", config.FilePath);
382 FileInfo fi = new FileInfo (config.FilePath);
383 Assert.AreEqual ("machineconfig", fi.Name);
387 public void exePath_UserLevelNone_null ()
390 SysConfig config = ConfigurationManager.OpenExeConfiguration (null);
391 Console.WriteLine("null exe application config path: {0}", config.FilePath);
393 FileInfo fi = new FileInfo (config.FilePath);
394 Assert.AreEqual (TestUtil.ThisConfigFileName, fi.Name);
399 [Category ("NotWorking")]
400 public void mapped_ExeConfiguration_null ()
402 SysConfig config = ConfigurationManager.OpenMappedExeConfiguration(null, ConfigurationUserLevel.None);
403 Console.WriteLine("null mapped application config path: {0}", config.FilePath);
405 FileInfo fi = new FileInfo (config.FilePath);
406 Assert.AreEqual (TestUtil.ThisConfigFileName, fi.Name);
410 [Category ("NotWorking")]
411 public void mapped_MachineConfig_null ()
413 SysConfig config = ConfigurationManager.OpenMappedMachineConfiguration (null);
414 Console.WriteLine("null mapped machine config path: {0}", config.FilePath);
416 FileInfo fi = new FileInfo (config.FilePath);
417 Assert.AreEqual ("machine.config", fi.Name);
421 public void GetSectionReturnsNativeObject ()
423 Assert.IsTrue (ConfigurationManager.GetSection ("appSettings") is NameValueCollection);
426 [Test] // test for bug #78372.
427 public void OpenMachineConfiguration ()
429 SysConfig cfg = ConfigurationManager.OpenMachineConfiguration ();
430 Assert.IsTrue (cfg.Sections.Count > 0, "#1");
431 ConfigurationSection s = cfg.SectionGroups ["system.net"].Sections ["connectionManagement"];
432 Assert.IsNotNull (s, "#2");
433 Assert.IsTrue (s is ConnectionManagementSection, "#3");
437 public void SectionCollectionEnumerator ()
439 SysConfig c = ConfigurationManager.OpenExeConfiguration (ConfigurationUserLevel.None);
440 ConfigurationSectionCollection col =
441 c.GetSectionGroup ("system.web").Sections;
442 IEnumerator e = col.GetEnumerator ();
444 Assert.IsTrue (e.Current is ConfigurationSection);
447 [Test] // Test for bug #3412
448 [Category("NotWorking")]
449 public void TestAddRemoveSection()
451 const string name = "testsection";
452 var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
454 // ensure not present
455 if (config.Sections.Get(name) != null)
457 config.Sections.Remove(name);
461 config.Sections.Add(name, new TestSection());
464 var section = config.Sections.Get(name);
465 Assert.IsNotNull(section);
466 Assert.IsNotNull(section as TestSection);
467 config.Sections.Remove(name);
470 config.Sections.Add(name, new TestSection());
473 section = config.Sections.Get(name);
474 Assert.IsNotNull(section);
475 Assert.IsNotNull(section as TestSection);
476 config.Sections.Remove(name);
480 public void TestFileMap ()
482 var name = Path.GetRandomFileName () + ".config";
483 Assert.IsFalse (File.Exists (name));
486 var map = new ExeConfigurationFileMap ();
487 map.ExeConfigFilename = name;
489 var config = ConfigurationManager.OpenMappedExeConfiguration (
490 map, ConfigurationUserLevel.None);
492 config.Sections.Add ("testsection", new TestSection ());
496 Assert.IsTrue (File.Exists (name), "#1");
497 Assert.IsTrue (File.Exists (Path.GetFullPath (name)), "#2");
504 public void TestContext ()
506 var config = ConfigurationManager.OpenExeConfiguration (ConfigurationUserLevel.None);
507 const string name = "testsection";
509 // ensure not present
510 if (config.GetSection (name) != null)
511 config.Sections.Remove (name);
513 var section = new TestContextSection ();
515 // Can't access EvaluationContext ....
517 section.TestContext (null);
519 } catch (ConfigurationException) {
523 // ... until it's been added to a section.
524 config.Sections.Add (name, section);
525 section.TestContext ("#2");
528 config.Sections.Remove (name);
530 // ... and it doesn't lose its context
531 section.TestContext (null);
535 public void TestContext2 ()
537 var name = Path.GetRandomFileName () + ".config";
538 Assert.IsFalse (File.Exists (name));
541 var map = new ExeConfigurationFileMap ();
542 map.ExeConfigFilename = name;
544 var config = ConfigurationManager.OpenMappedExeConfiguration (
545 map, ConfigurationUserLevel.None);
547 config.Sections.Add ("testsection", new TestSection ());
548 config.Sections.Add ("testcontext", new TestContextSection ());
552 Assert.IsTrue (File.Exists (name), "#1");
559 class TestSection : ConfigurationSection {}
561 class RemoteConfig : MarshalByRefObject
563 public static RemoteConfig GetInstance (AppDomain domain)
565 RemoteConfig config = (RemoteConfig) domain.CreateInstanceAndUnwrap (
566 typeof (RemoteConfig).Assembly.FullName,
567 typeof (RemoteConfig).FullName, new object [0]);
571 public string GetFilePath (string exePath)
573 global::System.Configuration.Configuration config =
574 ConfigurationManager.OpenExeConfiguration (exePath);
575 return config.FilePath;
578 public string GetFilePath (ConfigurationUserLevel userLevel)
580 global::System.Configuration.Configuration config =
581 ConfigurationManager.OpenExeConfiguration (userLevel);
582 return config.FilePath;
585 public string GetSettingValue (string exePath, string key)
587 global::System.Configuration.Configuration config =
588 ConfigurationManager.OpenExeConfiguration (exePath);
589 return config.AppSettings.Settings [key].Value;
592 public string GetSettingValue (ConfigurationUserLevel userLevel, string key)
594 global::System.Configuration.Configuration config =
595 ConfigurationManager.OpenExeConfiguration (userLevel);
596 KeyValueConfigurationElement value = config.AppSettings.Settings [key];
597 return value != null ? value.Value : null;
600 public string GetSettingValue (string key)
602 return ConfigurationManager.AppSettings [key];
606 class TestContextSection : ConfigurationSection {
607 public void TestContext (string label)
609 Assert.That (EvaluationContext != null, label);
615 public void TestConnectionStringRetrieval ()
617 var connStringObj = ConfigurationManager.ConnectionStrings ["test-connstring"];
618 Assert.IsNotNull (connStringObj);
619 var connString = connStringObj.ConnectionString;
620 Assert.IsFalse (String.IsNullOrEmpty (connString));
621 Assert.AreEqual ("Server=(local);Initial Catalog=someDb;User Id=someUser;Password=somePassword;Application Name=someAppName;Min Pool Size=5;Max Pool Size=500;Connect Timeout=10;Connection Lifetime=29;",
626 public void BadConfig ()
628 string xml = @" badXml";
630 var file = Path.Combine (tempFolder, "badConfig.config");
631 File.WriteAllText (file, xml);
634 var fileMap = new ConfigurationFileMap (file);
635 var configuration = ConfigurationManager.OpenMappedMachineConfiguration (fileMap);
636 Assert.Fail ("Exception ConfigurationErrorsException was expected.");
637 } catch (ConfigurationErrorsException e) {
638 Assert.AreEqual (file, e.Filename);