Loading...
Searching...
No Matches
HouseKeeper.cs
1using System;
2using System.Collections.Generic;
3using System.Diagnostics;
4using System.IO;
5using System.Text.RegularExpressions;
6using GAMS;
7using NLog;
8using NUnit.Framework;
9
10
11namespace GamsApiTests
12{
13 public class HouseKeeper
14 {
15 public static String gamsVersion = null;
16 public static String gamsSystemDir = null;
17 public static String gamsAbsoluteSystemDir = null;
18 public static String gamsWorkingDir = null;
19 public static String gamsAbsoluteWorkingDir = null;
20 public static String GDX_FILE_EXTENSION = ".gdx";
21 public static DebugLevel gamsDebugLevel = DebugLevel.Off;
22 static Logger logger = LogManager.GetCurrentClassLogger();
23
30 public static void prepare(String dir)
31 {
32 if (dir == null)
33 return;
34
35 if (!Directory.Exists(dir)){
36 logger.Debug("Creating Dir: " + dir);
37 Directory.CreateDirectory(dir);
38 }
39 else
40 {
41 logger.Debug("clear: " + dir);
42 clear(dir);
43 }
44 }
45
51 public static bool clear(String dir)
52
53 {
54 if (dir == null || !Directory.Exists(dir))
55 return false;
56
57 DirectoryInfo dirInfo = new DirectoryInfo(dir);
58
59 foreach (FileInfo file in dirInfo.GetFiles())
60 {
61 file.Delete();
62 }
63
64 foreach (DirectoryInfo di in dirInfo.GetDirectories())
65 {
66 clear(di.FullName);
67 di.Delete();
68 }
69 return true;
70 }
71
77 public static bool rcleanup(String dir)
78 {
79 if (dir != null && Directory.Exists(dir))
80 {
81 string[] files = Directory.GetFiles(dir);
82 foreach (string fileName in files)
83 File.Delete(fileName);
84
85 string[] subdirs = Directory.GetDirectories(dir);
86 foreach (string subdirectory in subdirs)
87 rcleanup(subdirectory);
88
89 Directory.Delete(dir);
90
91 }
92 // delete successful?
93 if (Directory.Exists(dir))
94 return false;
95 else
96 return true;
97 }
98
104 public static bool isGAMSDirectory(String dir)
105 {
106 return (Directory.Exists(dir) && (Directory.GetFiles(dir, "optgams.def").Length > 0));
107 }
108
114 public static void initializeTestFrom(String filename, String subdir)
115 {
116 String workingDir = null;
117
118 try
119 {
120 var properties = new Dictionary<string, string>();
121
122 // this seems to be necessary to run and debug tests with relative paths
123 Environment.CurrentDirectory = AppDomain.CurrentDomain.BaseDirectory;
124
125 FileInfo dbug = new FileInfo(filename);
126 foreach (var row in File.ReadAllLines(filename))
127 {
128 properties.Add(row.Split('=')[0].Trim(),
129 normalizePath(row.Split('=')[1].Trim()));
130 }
131
132 gamsVersion = properties["gamsVersion"];
133 gamsSystemDir = properties["gamsSystemDir"];
134 workingDir = properties["gamsWorkingDir"];
135
136 String path = Path.GetFullPath(workingDir + Path.DirectorySeparatorChar + subdir);
137 HouseKeeper.prepare(path);
138 gamsWorkingDir = Path.GetFullPath(path);
139 gamsDebugLevel = (DebugLevel)Enum.Parse(typeof(DebugLevel),
140 properties["gamsDebugLevel"], true);
141 }
142 catch (Exception e)
143 {
144 Debug.WriteLine(e.Message);
145 Assert.Fail("please check test configuration in [" + filename + "]");
146 }
147 Assert.NotNull(HouseKeeper.gamsVersion);
148 Assert.NotNull(HouseKeeper.gamsSystemDir);
149 Assert.NotNull(HouseKeeper.gamsWorkingDir);
150 Assert.NotNull(HouseKeeper.gamsDebugLevel);
151
152 Assert.True(Directory.Exists(HouseKeeper.gamsSystemDir),
153 "expect a valid gamsSystemDir being set in configuration file.");
154 HouseKeeper.gamsAbsoluteSystemDir = Path.GetFullPath(HouseKeeper.gamsSystemDir);
155
156 HouseKeeper.prepare(HouseKeeper.gamsWorkingDir);
157 HouseKeeper.clear(HouseKeeper.gamsWorkingDir);
158
159 HouseKeeper.gamsAbsoluteWorkingDir = Path.GetFullPath(HouseKeeper.gamsWorkingDir);
160 }
161
162 private static string normalizePath(string s)
163 {
164 Regex rgx = new Regex(@"\\*$");
165 string res = rgx.Replace(s, "");
166 return res;
167 }
168
177 {
178 // TODO: missing GAMSGlobals.OSType equivalent, check for other OSs
179 return findGAMS(Environment.GetEnvironmentVariable("DYLD_LIBRARY_PATH"));
180 }
181
187 {
188 return findGAMS(Environment.GetEnvironmentVariable("PATH").ToLower());
189 }
196 public static String findGAMS(String systemPath)
197 {
198 String GAMSDir = null;
199 if (systemPath != null && Directory.Exists(systemPath))
200 {
201 String callStr = "gams.exe"; // TODO: make dynamic, OS independent
202 foreach (var pathDir in systemPath.Split(Path.PathSeparator))
203 {
204 if(File.Exists(pathDir + Path.DirectorySeparatorChar + callStr)){
205 GAMSDir = Path.GetFullPath(pathDir);
206 }
207 }
208 }
209 return GAMSDir;
210 }
211
212 public static void delete(string dir)
213 {
214 var pathToBeDeleted = new DirectoryInfo(dir);
215 try
216 {
217 foreach (var file in pathToBeDeleted.EnumerateFiles("*", SearchOption.AllDirectories))
218 {
219 file.Delete();
220 }
221 pathToBeDeleted.Delete(true);
222 }
223 catch (IOException e) { Console.WriteLine(e.Message); }
224 }
225
226
227 public static bool PrepareDatabaseFrom(string library, string model, string workingdir)
228 {
229 int exit = -1;
230 try
231 {
232 List<string> arguments = new List<string>();
233 arguments.Add(library);
234 arguments.Add(model);
235
236 ProcessStartInfo psi = new ProcessStartInfo();
237 psi.FileName = arguments[0];
238 psi.Arguments = string.Join(" ", arguments.GetRange(1, arguments.Count - 1));
239 psi.WorkingDirectory = workingdir;
240
241 using (Process p = Process.Start(psi))
242 {
243 p.WaitForExit();
244 exit = p.ExitCode;
245 }
246 }
247 catch (IOException)
248 {
249 return false;
250 }
251 catch (Exception)
252 {
253 return false;
254 }
255 return (exit == 0);
256 }
257
258 public static GAMSJob CreateAndRunJobFromGamsLib(GAMSWorkspace ws, String lib)
259 {
260 // given
261 GAMSJob job = null;
262 try
263 {
264 // when, then
265 job = ws.AddJobFromGamsLib(lib);
266 Assert.NotNull(job, "expect a successful creation of job.");
267 }
268 catch (GAMSException)
269 {
270 Assert.Fail("do not expect an GAMSException to be raised.");
271 }
272 try
273 {
274 // when, then
275 job.Run();
276 Assert.NotNull(job, "expect a successful run.");
277 }
278 catch (GAMSException)
279 {
280 Assert.Fail("do not expect GAMSException when running a job.");
281 }
282
283 Assert.NotNull(job.OutDB, "do not expect an empty job output database.");
284
285 return job;
286 }
287
288 }
289}
GAMSDatabase OutDB
void Run(GAMSOptions gamsOptions=null, GAMSCheckpoint checkpoint=null, TextWriter output=null, Boolean createOutDB=true)
GAMSJob AddJobFromGamsLib(string model, GAMSCheckpoint checkpoint=null, string jobName=null)
static void prepare(String dir)
Prepare directory by checking its existence. If exists, (non - recursively) delete all its contents,...
Definition: HouseKeeper.cs:30
static String findGAMSFromPathEnvironmentVariable()
Find a valid GAMS system directory from environment.
Definition: HouseKeeper.cs:186
static bool clear(String dir)
(non-recursively) delete all contents under dir.
Definition: HouseKeeper.cs:51
static bool rcleanup(String dir)
(recursively) delete all contents under dir, and delete dir.
Definition: HouseKeeper.cs:77
static String findGAMS(String systemPath)
Find a valid GAMS system directory from the given path. A valid GAMS system directory contains a file...
Definition: HouseKeeper.cs:196
static String findGAMSFromAlternativeEnvironment()
Find a valid GAMS system directory from environment. in case of Windows: read from window registry "g...
Definition: HouseKeeper.cs:176
static void initializeTestFrom(String filename, String subdir)
initialize class properties from fileName and prepare directory subdir
Definition: HouseKeeper.cs:114
static bool isGAMSDirectory(String dir)
check a GAMS directory.
Definition: HouseKeeper.cs:104