classdef meq2eqdsk_test < meq_test
  % Test exporting MEQ structures to G-EQDSK file format
  %
  % [+MEQ MatlabEQuilibrium Toolbox+] Swiss Plasma Center EPFL Lausanne 2022. All rights reserved.
  
  properties
    tokamak = 'ana';
  end
  
  properties (TestParameter)
    shot = struct('limiter',1,'diverted',2);
  end
  
  methods(Test,TestTags={'Integration'})
    function test_meq2eqdsk(testCase,shot)
      
      tok = testCase.tokamak;
      t = 1; % Default time
     
      [L,~,LY] = fbt(tok,shot,t,'iterq',50);
      testCase.assertNotEmpty(LY,'FBT did not converge');

      % Convert to G-EQDSK
      fpath = tempname(); fname = 'eqdsk.meq';
      fullpath = fullfile(fpath,fname);
      mkdir(fpath);
      cleanupObj = onCleanup(@() rmdir(fpath,'s'));

      meq2eqdsk(L,LY,'fname',fullpath);

      testCase.verifyTrue(logical(exist(fullpath,'file')),sprintf('File %s was not created by meqweqdsk',fullpath));
    end

    function test_meq2eqdsk_fail(testCase)

      tok = testCase.tokamak;
      shot_ = 1; % Default limiter shot
      t = 1; % Default time

      % meq2eqdsk fails without FS integrals
      [L,~,LY] = fbt(tok,shot_,t,'iterq',0);
      testCase.assertNotEmpty(LY,'FBT did not converge');

      testCase.verifyError(@() meq2eqdsk(L,LY),'','meq2eqdsk did not throw the correct exception when provided LY without FS integrals');
    end

    function test_meq2eqdsk_cocos(testCase)

      tok = testCase.tokamak;
      shot_ = 1; % Default limiter shot
      t = 1; % Default time

      [L,~,LY] = fbt(tok,shot_,t,'iterq',50);
      testCase.assertNotEmpty(LY,'FBT did not converge');

      % Test that other values than 11 or 17 lead to errors
      for cocos = [1:8,11:18]
        switch cocos
          case {11,17}
            meq2eqdsk(L,LY,'cocos',cocos);
          otherwise
            testCase.verifyError(@() meq2eqdsk(L,LY,'cocos',cocos),'meq2eqdsk:cocos',sprintf('meq2eqdsk did not throw an exception with cocos=%d',cocos));
        end
      end
    end
  end

  methods(Test,TestTags={'TCV'})
    function test_meq2eqdsk_bffbt(testCase)
      [L,~,LY] = fbt('tcv',55555,1,'iterq',50);
      testCase.assertNotEmpty(LY,'FBT did not converge');

      % Test handling of legacy bfp parameters
      meq2eqdsk(L,LY);
    end
  end
end
