function Results = Tester
% Truss Files Tests
% Copyright 2015 The MathWorks, Inc.

    % Make sure we're on R2013b or newer
    if verLessThan('matlab','8.2')
        ME = MException('pct:truss','R2013b or newer required for this demo');
        throwAsCaller(ME);
    end

    % Get local functions and test functions from this
    lfs = localfunctions();
    tests = functiontests(lfs);
    
    % Run 'em
    Results = run(tests);    

end

%Test functions
function testFilesExist(testCase)
% Check that all expected files exist
% Add files to test to this list.  Use *.m extension.
reqFiles = {'localStiffness.m'; ...
    'batchODE.m'; ...
    'clusterBatch.m'; ...
    'paramSweep.m'; ...
    'paramSweepBreak.m'; ...
    'paramSweepBreakParfeval.m'; ...
    'paramSweepParallel.m'; ...
    'plotTruss.m'; ...
    'trussCantilever.m'; ...
    'visualizeParamSweep.m'};

% Actual Files
pwdFiles = dir([pwd,filesep,'*.m']);
pwdFiles = {pwdFiles.name};

% Membership
idx = ismember(reqFiles,pwdFiles);

% Import constraints
import matlab.unittest.constraints.IsTrue
import matlab.unittest.constraints.EveryElementOf

% Qualify
verifyThat(testCase,EveryElementOf(idx),IsTrue,...
    sprintf('%s missing\n',reqFiles{~idx}))

end

function testParpoolWorking(testCase)
% Build a pool
p = gcp('nocreate');

if isempty(p)
    p = gcp;
    alreadyOpen = false;
else
    alreadyOpen = true;
end

% Test that it's connected and on local profile
verifyTrue(testCase,p.Connected,'Pool is not connected');
assumeMatches(testCase,p.Cluster.Profile,'local','Local pool is not current\n');

% If we opened the pool, close it
if ~alreadyOpen
    delete(p);
end

end

function testLoopIsFor(testCase)
% Test that paramSweep has been set back to use a "for" loop since last run

% Open file and make sure the loop is a "for"
fid = fopen('paramSweep.m','r');

% Over-preallocate
Cfile = cell(200,1);

% Read each row into a string (see fgetl doc)
cnt = 1;
tline = fgetl(fid);
while ischar(tline)
    Cfile{cnt} = tline;
    
    % Increment and read next line
    cnt = cnt + 1;
    tline = fgetl(fid);
    
end

% Lop off extra lines
Cfile = Cfile(~cellfun(@isempty,Cfile));

% Clean up
fclose(fid);

% Import constraints
import matlab.unittest.constraints.AnyCellOf
import matlab.unittest.constraints.EveryCellOf
import matlab.unittest.constraints.Matches

% Qualify for/parfor
% Has a "for ii" and not a "parfor ii"
assertThat(testCase,AnyCellOf(Cfile),Matches('^for'),'"for" does not start a line');
assertThat(testCase,EveryCellOf(Cfile),~Matches('^parfor'),'"parfor" starts a line');

end

% Turn off code analyzer warning for unused functions since localfunctions
% captures this.
%#ok<*DEFNU>