%

% Copyright 2012-2019 The MathWorks, Inc.

classdef LocalTest < coder.rtiostreamtest.TestDecorator
%FASTTESTMYRESULTS creates a connection with the precompiled server
% Spawns a new server and establishes connection with it. It then
% passes the new instance of the server to the enclosed test so
% that you can transparently run a test onto a locally run server.
%
% Parameters:
% binary -
% The name of the executable (full location)
%

% Available parameters defined here
properties (Constant)
param_binary = 'binary';

% Default name of the executable. Don't use extensions.
default_exePath = fullfile(matlabroot, 'bin', ...
computer('arch'), 'rtiostreamtest_host');
end

properties
% A string with the protocol that would be tested
protocol;
end

methods

function this = LocalTest(test, protocol)
% TEST must have exactly one output
if nargin == 1, protocol = 'TCP'; end

protocol = upper(protocol);
this = this@coder.rtiostreamtest.TestDecorator(test);
this.protocol = protocol;
end

function result = runTest(this, ~, parameters)

import coder.rtiostreamtest.*;

% Parse parameters
exePath = Test.getSetting(parameters, LocalTest.param_binary, this.default_exePath);
if ispc
exePath = [exePath '.exe'];
end

% Start server and get port
compArgs = coder.connectivity.ComponentArgs('','','','');
compArgs.setClientInterface(coder.rtiostreamtest.ClientInterface);
serverLauncher = rtw.connectivity.HostLauncher(compArgs);
% run in blocking mode to avoid polling which can consume a lot
% of host CPU cycles
serverLauncher.setArgString(['-client 0 -blocking 1 -protocol ' this.protocol ' -port 0']);
serverLauncher.setExe(exePath);
serverLauncher.startApplication;
port = rtw.connectivity.HostTCPIPCommunicator.parseOutputFileForServerPort(serverLauncher);

% Initialize connection
paramProvider = Parameters.getParameterInstance(this.protocol, {'localhost', port});
[library, libpars] = paramProvider.getSharedLibrary();

connection = coder.rtiostreamtest.ServerConnection(library, libpars, false);

% Conduct test
result = this.test.runTest(connection, parameters);
% clean up ServerConnection before HostLauncher to make sure
% shutdown occurs before the application is terminated
clear connection;
end

end

end