classdef writestruct_test < genlib_test
  % Testclass for writeclass
  %
  % [+GenLib General Purpose Library+] Swiss Plasma Center EPFL Lausanne 2022. All rights reserved.

  properties (TestParameter)
    % a challenging structure
    S = {struct('x',rand(1),...
                'y',int16(2),...
                'z',rand(3),...
                'n',2,...
                'r',struct('x',1,'y',2),...
                's','bla',...
                'a',int16(rand(1,4)),...
                'b',[true;false],...
                'es',struct(),...
                'c',{{1,{{2,3}},rand(2),num2cell(rand(2))}},...
                'cs',{{1,struct('a',1,'b',struct('c','cc','a',{{1,2,3}}))}},... % cell containing struct with nested struct with cell
                'sa',struct(repmat(struct('a',1,'b',2),3,2))),... % array of structures
        };
  end
  
  properties
    tempdir
  end
  
  methods (TestClassSetup)
    function temporary_directory(testCase)
      testCase.tempdir = tempname;
      testCase.assertTrue(mkdir(testCase.tempdir));
      testCase.addTeardown(@() rmdir(testCase.tempdir,'s'));
    end
  end
  
  methods (Test)
    function test_writestruct(testCase,S)
      S = orderfields(S);
  
      testCase.addTeardown(@() rmpath(testCase.tempdir));
      addpath(testCase.tempdir);
      %% write file
      fname = fullfile(testCase.tempdir,'testStruct.m');
      testCase.addTeardown(@() delete(fname));
      ok=writestruct(S,fname);
      testCase.assertTrue(ok,'error writing struct');
  
      %% read
      testCase.assertTrue(exist(fname,'file')>0,sprintf('%s does not exist',fname));
      Sout = testStruct;
      
      %% test that they are equal
      testCase.verifyTrue(structcmp(S,Sout,1e-5));
    end
  end
end
