common_test

v1.30

ct

Main user interface for the Common Test framework.

This module implements the command-line interface for running tests and basic functions for Common Test case issues, such as configuration and logging.

The framework stores configuration values in a property list usually named Config. The list contains information about the test run added by the framework itself and may also contain user-provided values. The configuration is passed into individual test cases as well as support functions if defined.

Possible configuration variables include:

data_dir - Data file directory

priv_dir - Scratch file directory

Whatever added by init_per_suite/1 or init_per_testcase/2 in the test suite.

Warning

The ?config macro, used to receive individual config values from the Config property list, is deprecated. Please use proplists:get_value/2-3 instead.

Summary

Types

config_key()

A configuration key which exists in a configuration file

conn_log_mod()

conn_log_option()

conn_log_options()

Options that can be given to the cth_conn_log hook, which is used for logging of NETCONF and Telnet connections. See ct_netconfc or ct_telnet for description and examples of how to use this hook.

conn_log_type()

handle()

The identity (handle) of a connection.

key_or_name()

target_name()

A name and association to configuration data introduced through a require statement, or a call to ct:require/2, for example, ct:require(mynodename,{node,[telnet]}).

Functions

abort_current_testcase(Reason)

Aborts the currently executing test case. The user must know with certainty which test case is currently executing. The function is therefore only safe to call from a function that has been called (or synchronously invoked) by the test case.

add_config(Callback, Config)

Loads configuration variables using the specified callback module and configuration string. The callback module is to be either loaded or present in the code path. Loaded configuration variables can later be removed using function ct:remove_config/2.

break(Comment)

Cancels any active timetrap and pauses the execution of the current test case until the user calls function continue/0. The user can then interact with the Erlang node running the tests, for example, for debugging purposes or for manually executing a part of the test case. If a parallel group is executing, ct:break/2 is to be called instead.

break(TestCase, Comment)

Works the same way as ct:break/1, only argument TestCase makes it possible to pause a test case executing in a parallel group. Function ct:continue/1 is to be used to resume execution of TestCase.

capture_get()

Equivalent to capture_get([default]).

capture_get(ExclCategories)

Returns and purges the list of text strings buffered during the latest session of capturing printouts to stdout. Log categories that are to be ignored in ListOfStrings can be specified with ExclCategories. If ExclCategories = [], no filtering takes place.

capture_start()

Starts capturing all text strings printed to stdout during execution of the test case.

capture_stop()

Stops capturing text strings (a session started with capture_start/0).

comment(Comment)

Prints the specified Comment in the comment field in the table on the test suite result page.

comment(Format, Args)

Prints the formatted string in the comment field in the table on the test suite result page.

continue()

This function must be called to continue after a test case (not executing in a parallel group) has called function ct:break/1.

continue(TestCase)

This function must be called to continue after a test case has called ct:break/2. If the paused test case, TestCase, executes in a parallel group, this function, rather than continue/0, must be used to let the test case proceed.

decrypt_config_file(EncryptFileName, TargetFileName)

Decrypts EncryptFileName, previously generated with ct:encrypt_config_file/2,3. The original file contents is saved in the target file. The encryption key, a string, must be available in a text file named .ct_config.crypt, either in the current directory, or the home directory of the user (it is searched for in that order).

decrypt_config_file(EncryptFileName, TargetFileName, KeyOrFile)

Decrypts EncryptFileName, previously generated with ct:encrypt_config_file/2,3. The original file contents is saved in the target file. The key must have the same value as that used for encryption.

encrypt_config_file(SrcFileName, EncryptFileName)

Encrypts the source configuration file with DES3 and saves the result in file EncryptFileName. The key, a string, must be available in a text file named .ct_config.crypt, either in the current directory, or the home directory of the user (it is searched for in that order).

encrypt_config_file(SrcFileName, EncryptFileName, KeyOrFile)

Encrypts the source configuration file with DES3 and saves the result in the target file EncryptFileName. The encryption key to use is either the value in {key,Key} or the value stored in the file specified by {file,File}.

fail(Reason)

Terminates a test case with the specified error Reason.

fail(Format, Args)

Terminates a test case with an error message specified by a format string and a list of values (used as arguments to io_lib:format/2).

get_config(Required)

Equivalent to get_config(Required, undefined, []).

get_config(Required, Default)

Equivalent to get_config(Required, Default, []).

get_config(Required, Default, Opts)

Reads configuration data values.

get_event_mgr_ref()

Gets a reference to the Common Test event manager. The reference can be used to, for example, add a user-specific event handler while tests are running.

get_progname()

Returns the command used to start this Erlang instance. If this information could not be found, the string "no_prog_name" is returned.

get_status()

Returns status of ongoing test. The returned list contains information about which test case is executing (a list of cases when a parallel test case group is executing), as well as counters for successful, failed, skipped, and total test cases so far.

get_target_name(Handle)

Returns the name of the target that the specified connection belongs to.

get_testspec_terms()

Gets a list of all test specification terms used to configure and run this test.

get_testspec_terms(Tags)

Reads one or more terms from the test specification used to configure and run this test. Tag is any valid test specification tag, for example, label, config, or logdir. User-specific terms are also available to read if option allow_user_terms is set.

get_timetrap_info()

Reads information about the timetrap set for the current test case. Scaling indicates if Common Test will attempt to compensate timetraps automatically for runtime delays introduced by, for example, tools like cover. ScaleVal is the value of the current scaling multiplier (always 1 if scaling is disabled). Note the Time is not the scaled result.

get_verbosity(Category)

This function returns the verbosity level for the specified logging category. See the User's Guide for details. Use the value default to read the general verbosity level.

install(Opts)

Installs configuration files and event handlers.

listenv(Telnet)

Performs command listenv on the specified Telnet connection and returns the result as a list of key-value pairs.

log(Format)

Equivalent to log(default, ?STD_IMPORTANCE, Format, [], []).

log(X1, X2)

Equivalent to log(Category, Importance, Format, FormatArgs, []).

log(X1, X2, X3)

Equivalent to log(Category, Importance, Format, FormatArgs, Opts).

log(X1, X2, X3, X4)

Equivalent to log(Category, Importance, Format, FormatArgs, Opts).

log(Category, Importance, Format, FormatArgs, Opts)

Prints from a test case to the log file.

make_priv_dir()

If the test is started with option create_priv_dir set to manual_per_tc, in order for the test case to use the private directory, it must first create it by calling this function.

notify(Name, Data)

Sends an asynchronous notification of type Name with Datato the Common Test event manager. This can later be caught by any installed event manager.

pal(Format)

Equivalent to pal(default, ?STD_IMPORTANCE, Format, []).

pal(X1, X2)

Equivalent to pal(Category, Importance, Format, FormatArgs, []).

pal(X1, X2, X3)

Equivalent to pal(Category, Importance, Format, FormatArgs, Opts).

pal(X1, X2, X3, X4)

Equivalent to pal(Category, Importance, Format, FormatArgs, Opts).

pal(Category, Importance, Format, FormatArgs, Opts)

Prints and logs from a test case.

parse_table(Data)

Parses the printout from an SQL table and returns a list of tuples.

print(Format)

Equivalent to print(default, ?STD_IMPORTANCE, Format, [], []).

print(X1, X2)

Equivalent to print(Category, Importance, Format, FormatArgs, []).

print(X1, X2, X3)

Equivalent to print(Category, Importance, Format, FormatArgs, Opts).

print(X1, X2, X3, X4)

Equivalent to print(Category, Importance, Format, FormatArgs, Opts).

print(Category, Importance, Format, FormatArgs, Opts)

Prints from a test case to the console.

reload_config(Required)

Reloads configuration file containing specified configuration key.

remaining_test_procs()

This function will return the identity of test- and group leader processes that are still running at the time of this call. TestProcs are processes in the system that have a Common Test IO process as group leader. SharedGL is the central Common Test IO process, responsible for printing to log files for configuration functions and sequentially executing test cases. OtherGLs are Common Test IO processes that print to log files for test cases in parallel test case groups.

remove_config(Callback, Config)

Removes configuration variables (together with their aliases) that were loaded with specified callback module and configuration string.

require(Required)

Checks if the required configuration is available. Arbitrarily deep tuples can be specified as Required. Only the last element of the tuple can be a list of SubKeys.

require(Name, Required)

Checks if the required configuration is available and gives it a name. The semantics for Required is the same as in ct:require/1 except that a list of SubKeys cannot be specified.

run(TestDirs)

Runs all test cases in all suites in the specified directories.

run(TestDir, Suite)

Runs all test cases in the specified suite.

run(TestDir, Suite, Cases)

Runs the specified test cases.

run_test(Opts)

Runs tests as specified by the combination of options in Opts. The options are the same as those used with program ct_run, see Run Tests from Command Line in the ct_run manual page.

run_testspec(TestSpec)

Runs a test specified by TestSpec. The same terms are used as in test specification files.

set_verbosity(Category, Level)

Use this function to set, or modify, the verbosity level for a logging category. See the User's Guide for details. Use the value default to set the general verbosity level.

sleep(Time)

This function, similar to timer:sleep/1 in STDLIB, suspends the test case for a specified time. However, this function also multiplies Time with the multiply_timetraps value (if set) and under certain circumstances also scales up the time automatically if scale_timetraps is set to true (default is false).

start_interactive()

Starts Common Test in interactive mode.

step(TestDir, Suite, Case)

Steps through a test case with the debugger.

step(TestDir, Suite, Case, Opts)

Steps through a test case with the debugger. If option config has been specified, breakpoints are also set on the configuration functions in Suite.

stop_interactive()

Exits the interactive mode.

sync_notify(Name, Data)

Sends a synchronous notification of type Name with Data to the Common Test event manager. This can later be caught by any installed event manager.

testcases(TestDir, Suite)

Returns all test cases in the specified suite.

timetrap(Time)

Sets a new timetrap for the running test case.

userdata(TestDir, Suite)

Returns any data specified with tag userdata in the list of tuples returned from suite/0.

userdata(TestDir, Suite, Case)

Returns any data specified with tag userdata in the list of tuples returned from Suite:group(GroupName) or Suite:Case().

Types

config_key()

-type config_key() :: atom().

A configuration key which exists in a configuration file

conn_log_mod()

-type conn_log_mod() :: ct_netconfc | ct_telnet.

conn_log_option()

-type conn_log_option() :: {log_type, conn_log_type()} | {hosts, [key_or_name()]}.

conn_log_options()

-type conn_log_options() :: [conn_log_option()].

Options that can be given to the cth_conn_log hook, which is used for logging of NETCONF and Telnet connections. See ct_netconfc or ct_telnet for description and examples of how to use this hook.

conn_log_type()

-type conn_log_type() :: raw | pretty | html | silent.

handle()

-type handle() :: pid().

The identity (handle) of a connection.

key_or_name()

-type key_or_name() :: config_key() | target_name().

target_name()

-type target_name() :: atom().

A name and association to configuration data introduced through a require statement, or a call to ct:require/2, for example, ct:require(mynodename,{node,[telnet]}).

Functions

abort_current_testcase(Reason)

-spec abort_current_testcase(Reason) -> ok | {error, ErrorReason}
                                when
                                    Reason :: term(),
                                    ErrorReason :: no_testcase_running | parallel_group.

Aborts the currently executing test case. The user must know with certainty which test case is currently executing. The function is therefore only safe to call from a function that has been called (or synchronously invoked) by the test case.

Reason, the reason for aborting the test case, is printed in the test case log.

add_config(Callback, Config)

(since OTP R14B)

-spec add_config(Callback, Config) -> ok | {error, Reason}
                    when Callback :: atom(), Config :: string(), Reason :: term().

Loads configuration variables using the specified callback module and configuration string. The callback module is to be either loaded or present in the code path. Loaded configuration variables can later be removed using function ct:remove_config/2.

break(Comment)

(since OTP R15B02)

-spec break(Comment) -> ok | {error, Reason}
               when
                   Comment :: string(),
                   Reason ::
                       {multiple_cases_running, TestCases} | 'enable break with release_shell option',
                   TestCases :: [atom()].

Cancels any active timetrap and pauses the execution of the current test case until the user calls function continue/0. The user can then interact with the Erlang node running the tests, for example, for debugging purposes or for manually executing a part of the test case. If a parallel group is executing, ct:break/2 is to be called instead.

A cancelled timetrap is not automatically reactivated after the break, but must be started explicitly with ct:timetrap/1.

In order for the break/continue functionality to work, Common Test must release the shell process controlling stdin. This is done by setting start option release_shell to true. For details, see section Running Tests from the Erlang Shell or from an Erlang Program in the User's Guide.

break(TestCase, Comment)

(since OTP R15B02)

-spec break(TestCase, Comment) -> ok | {error, Reason}
               when
                   TestCase :: atom(),
                   Comment :: string(),
                   Reason :: 'test case not running' | 'enable break with release_shell option'.

Works the same way as ct:break/1, only argument TestCase makes it possible to pause a test case executing in a parallel group. Function ct:continue/1 is to be used to resume execution of TestCase.

For details, see ct:break/1.

capture_get()

(since OTP R15B)

-spec capture_get() -> ListOfStrings when ListOfStrings :: [string()].

Equivalent to capture_get([default]).

capture_get(ExclCategories)

(since OTP R15B)

-spec capture_get(ExclCategories) -> ListOfStrings
                     when ExclCategories :: [atom()], ListOfStrings :: [string()].

Returns and purges the list of text strings buffered during the latest session of capturing printouts to stdout. Log categories that are to be ignored in ListOfStrings can be specified with ExclCategories. If ExclCategories = [], no filtering takes place.

See also ct:capture_start/0, ct:capture_stop/0, ct:log/3.

capture_start()

(since OTP R15B)

-spec capture_start() -> ok.

Starts capturing all text strings printed to stdout during execution of the test case.

See also ct:capture_get/1, ct:capture_stop/0.

capture_stop()

(since OTP R15B)

-spec capture_stop() -> ok.

Stops capturing text strings (a session started with capture_start/0).

See also ct:capture_get/1, ct:capture_start/0.

comment(Comment)

-spec comment(Comment) -> ok when Comment :: term().

Prints the specified Comment in the comment field in the table on the test suite result page.

If called several times, only the last comment is printed. The test case return value {comment,Comment} overwrites the string set by this function.

Warning

This function (and ct:comment/2) should only be called from the process running the common_test functions, typically the test case process or its descendant. Be aware that if you spawn a new process in one common_test function (e.g. init_per_suite) and then execute ct:comment/1-2 in that new process while the test execution has moved to another common_test function (e.g. init_per_testcase or test case function) the comment might not be printed in the correct place in HTML logs or at all.

Calling this function from a process that is neither a common_test process, nor its descendant does not result in the comment being printed anywhere.

comment(Format, Args)

(since OTP R15B)

-spec comment(Format, Args) -> ok when Format :: string(), Args :: list().

Prints the formatted string in the comment field in the table on the test suite result page.

Arguments Format and Args are used in a call to io_lib:format/2 to create the comment string. The behavior of comment/2 is otherwise the same as function ct:comment/1.

continue()

(since OTP R15B02)

-spec continue() -> ok.

This function must be called to continue after a test case (not executing in a parallel group) has called function ct:break/1.

continue(TestCase)

(since OTP R15B02)

-spec continue(TestCase) -> ok when TestCase :: atom().

This function must be called to continue after a test case has called ct:break/2. If the paused test case, TestCase, executes in a parallel group, this function, rather than continue/0, must be used to let the test case proceed.

decrypt_config_file(EncryptFileName, TargetFileName)

-spec decrypt_config_file(EncryptFileName, TargetFileName) -> ok | {error, Reason}
                             when
                                 EncryptFileName :: string(),
                                 TargetFileName :: string(),
                                 Reason :: term().

Decrypts EncryptFileName, previously generated with ct:encrypt_config_file/2,3. The original file contents is saved in the target file. The encryption key, a string, must be available in a text file named .ct_config.crypt, either in the current directory, or the home directory of the user (it is searched for in that order).

decrypt_config_file(EncryptFileName, TargetFileName, KeyOrFile)

-spec decrypt_config_file(EncryptFileName, TargetFileName, KeyOrFile) -> ok | {error, Reason}
                             when
                                 EncryptFileName :: string(),
                                 TargetFileName :: string(),
                                 KeyOrFile :: {key, string()} | {file, string()},
                                 Reason :: term().

Decrypts EncryptFileName, previously generated with ct:encrypt_config_file/2,3. The original file contents is saved in the target file. The key must have the same value as that used for encryption.

encrypt_config_file(SrcFileName, EncryptFileName)

-spec encrypt_config_file(SrcFileName, EncryptFileName) -> ok | {error, Reason}
                             when SrcFileName :: string(), EncryptFileName :: string(), Reason :: term().

Encrypts the source configuration file with DES3 and saves the result in file EncryptFileName. The key, a string, must be available in a text file named .ct_config.crypt, either in the current directory, or the home directory of the user (it is searched for in that order).

For information about using encrypted configuration files when running tests, see section Encrypted Configuration Files in the User's Guide.

For details on DES3 encryption/decryption, see application Crypto.

encrypt_config_file(SrcFileName, EncryptFileName, KeyOrFile)

-spec encrypt_config_file(SrcFileName, EncryptFileName, KeyOrFile) -> ok | {error, Reason}
                             when
                                 SrcFileName :: string(),
                                 EncryptFileName :: string(),
                                 KeyOrFile :: {key, string()} | {file, string()},
                                 Reason :: term().

Encrypts the source configuration file with DES3 and saves the result in the target file EncryptFileName. The encryption key to use is either the value in {key,Key} or the value stored in the file specified by {file,File}.

For information about using encrypted configuration files when running tests, see section Encrypted Configuration Files in the User's Guide.

For details on DES3 encryption/decryption, see application Crypto.

fail(Reason)

-spec fail(Reason) -> no_return() when Reason :: term().

Terminates a test case with the specified error Reason.

fail(Format, Args)

(since OTP R15B)

-spec fail(Format, Args) -> no_return() when Format :: io:format(), Args :: [term()].

Terminates a test case with an error message specified by a format string and a list of values (used as arguments to io_lib:format/2).

get_config(Required)

-spec get_config(Required) -> Value
                    when
                        Required :: KeyOrName | {KeyOrName, SubKey} | {KeyOrName, SubKey, SubKey},
                        KeyOrName :: key_or_name(),
                        SubKey :: atom(),
                        Value :: term().

Equivalent to get_config(Required, undefined, []).

get_config(Required, Default)

-spec get_config(Required, Default) -> Value
                    when
                        Required :: KeyOrName | {KeyOrName, SubKey} | {KeyOrName, SubKey, SubKey},
                        KeyOrName :: key_or_name(),
                        SubKey :: atom(),
                        Default :: term(),
                        Value :: term().

Equivalent to get_config(Required, Default, []).

get_config(Required, Default, Opts)

-spec get_config(Required, Default, Opts) -> ValueOrElement
                    when
                        Required :: KeyOrName | {KeyOrName, SubKey} | {KeyOrName, SubKey, SubKey},
                        KeyOrName :: key_or_name(),
                        SubKey :: atom(),
                        Default :: term(),
                        Opts :: [Opt],
                        Opt :: element | all,
                        ValueOrElement :: term() | Default.

Reads configuration data values.

Returns the matching values or configuration elements, given a configuration variable key or its associated name (if one has been specified with ct:require/2 or a require statement).

Example:

Given the following configuration file:

{unix,[{telnet,IpAddr},
       {user,[{username,Username},
              {password,Password}]}]}.

Then:

ct:get_config(unix,Default) -> [{telnet,IpAddr},
 {user, [{username,Username}, {password,Password}]}]
ct:get_config({unix,telnet},Default) -> IpAddr
ct:get_config({unix,user,username},Default) -> Username
ct:get_config({unix,ftp},Default) -> Default
ct:get_config(unknownkey,Default) -> Default

If a configuration variable key has been associated with a name (by ct:require/2 or a require statement), the name can be used instead of the key to read the value:

ct:require(myuser,{unix,user}) -> ok.
ct:get_config(myuser,Default) -> [{username,Username}, {password,Password}]

If a configuration variable is defined in multiple files, use option all to access all possible values. The values are returned in a list. The order of the elements corresponds to the order that the configuration files were specified at startup.

If configuration elements (key-value tuples) are to be returned as result instead of values, use option element. The returned elements are then on the form {Required,Value}.

See also ct:get_config/1, ct:get_config/2, ct:require/1, ct:require/2.

get_event_mgr_ref()

(since OTP 17.5)

-spec get_event_mgr_ref() -> EvMgrRef when EvMgrRef :: atom().

Gets a reference to the Common Test event manager. The reference can be used to, for example, add a user-specific event handler while tests are running.

Example:

gen_event:add_handler(ct:get_event_mgr_ref(), my_ev_h, [])

get_progname()

(since OTP 21.0)

-spec get_progname() -> string().

Returns the command used to start this Erlang instance. If this information could not be found, the string "no_prog_name" is returned.

get_status()

-spec get_status() -> TestStatus | {error, Reason} | no_tests_running
                    when
                        TestStatus :: [StatusElem],
                        StatusElem ::
                            {current, TestCaseInfo} |
                            {successful, Successful} |
                            {failed, Failed} |
                            {skipped, Skipped} |
                            {total, Total},
                        TestCaseInfo :: {Suite, TestCase} | [{Suite, TestCase}],
                        Suite :: atom(),
                        TestCase :: atom(),
                        Successful :: integer(),
                        Failed :: integer(),
                        Skipped :: {UserSkipped, AutoSkipped},
                        UserSkipped :: integer(),
                        AutoSkipped :: integer(),
                        Total :: integer(),
                        Reason :: term().

Returns status of ongoing test. The returned list contains information about which test case is executing (a list of cases when a parallel test case group is executing), as well as counters for successful, failed, skipped, and total test cases so far.

get_target_name(Handle)

-spec get_target_name(Handle) -> {ok, TargetName} | {error, Reason}
                         when Handle :: handle(), TargetName :: target_name(), Reason :: term().

Returns the name of the target that the specified connection belongs to.

get_testspec_terms()

(since OTP 18.0)

-spec get_testspec_terms() -> TestSpecTerms | undefined
                            when TestSpecTerms :: [{Tag, Value}], Tag :: atom(), Value :: [term()].

Gets a list of all test specification terms used to configure and run this test.

get_testspec_terms(Tags)

(since OTP 18.0)

-spec get_testspec_terms(Tags) -> TestSpecTerms | undefined
                            when
                                Tags :: [Tag] | Tag,
                                Tag :: atom(),
                                TestSpecTerms :: [{Tag, Value}] | {Tag, Value},
                                Value :: [{Node, term()}] | [term()],
                                Node :: atom().

Reads one or more terms from the test specification used to configure and run this test. Tag is any valid test specification tag, for example, label, config, or logdir. User-specific terms are also available to read if option allow_user_terms is set.

All value tuples returned, except user terms, have the node name as first element.

To read test terms, use Tag = tests (rather than suites, groups, or cases). Value is then the list of all tests on the form [{Node,Dir,[{TestSpec,GroupsAndCases1},...]},...], where GroupsAndCases = [{Group,[Case]}] | [Case].

get_timetrap_info()

(since OTP R15B)

-spec get_timetrap_info() -> {Time, {Scaling, ScaleVal}}
                           when Time :: timeout(), Scaling :: boolean(), ScaleVal :: integer().

Reads information about the timetrap set for the current test case. Scaling indicates if Common Test will attempt to compensate timetraps automatically for runtime delays introduced by, for example, tools like cover. ScaleVal is the value of the current scaling multiplier (always 1 if scaling is disabled). Note the Time is not the scaled result.

get_verbosity(Category)

(since OTP 19.1)

-spec get_verbosity(Category) -> Level | undefined when Category :: default | atom(), Level :: integer().

This function returns the verbosity level for the specified logging category. See the User's Guide for details. Use the value default to read the general verbosity level.

install(Opts)

-spec install(Opts) -> ok | {error, Reason}
                 when
                     Opts :: [Opt],
                     Opt :: {config, ConfigFiles} | {event_handler, Modules} | {decrypt, KeyOrFile},
                     ConfigFiles :: [ConfigFile],
                     ConfigFile :: string(),
                     Modules :: [atom()],
                     KeyOrFile :: {key, Key} | {file, KeyFile},
                     Key :: string(),
                     KeyFile :: string(),
                     Reason :: term().

Installs configuration files and event handlers.

Run this function once before the first test.

Example:

install([{config,["config_node.ctc","config_user.ctc"]}])

This function is automatically run by program ct_run.

listenv(Telnet)

-spec listenv(Telnet) -> {ok, [Env]} | {error, Reason}
                 when
                     Telnet :: ct_telnet:connection(),
                     Env :: {Key, Value},
                     Key :: string(),
                     Value :: string(),
                     Reason :: term().

Performs command listenv on the specified Telnet connection and returns the result as a list of key-value pairs.

log(Format)

-spec log(Format) -> ok when Format :: string().

Equivalent to log(default, ?STD_IMPORTANCE, Format, [], []).

log(X1, X2)

-spec log(X1, X2) -> ok
             when
                 X1 :: Category | Importance | Format,
                 X2 :: Format | FormatArgs,
                 Category :: atom() | integer() | string(),
                 Importance :: integer(),
                 Format :: string(),
                 FormatArgs :: list().

Equivalent to log(Category, Importance, Format, FormatArgs, []).

log(X1, X2, X3)

-spec log(X1, X2, X3) -> ok
             when
                 X1 :: Category | Importance,
                 X2 :: Importance | Format,
                 X3 :: Format | FormatArgs | Opts,
                 Category :: atom() | integer() | string(),
                 Importance :: integer(),
                 Format :: string(),
                 FormatArgs :: list(),
                 Opts :: [Opt],
                 Opt :: {heading, string()} | no_css | esc_chars.

Equivalent to log(Category, Importance, Format, FormatArgs, Opts).

log(X1, X2, X3, X4)

(since OTP R15B02)

-spec log(X1, X2, X3, X4) -> ok
             when
                 X1 :: Category | Importance,
                 X2 :: Importance | Format,
                 X3 :: Format | FormatArgs,
                 X4 :: FormatArgs | Opts,
                 Category :: atom() | integer() | string(),
                 Importance :: integer(),
                 Format :: string(),
                 FormatArgs :: list(),
                 Opts :: [Opt],
                 Opt :: {heading, string()} | no_css | esc_chars.

Equivalent to log(Category, Importance, Format, FormatArgs, Opts).

log(Category, Importance, Format, FormatArgs, Opts)

(since OTP 18.3)

-spec log(Category, Importance, Format, FormatArgs, Opts) -> ok
             when
                 Category :: atom() | integer() | string(),
                 Importance :: integer(),
                 Format :: string(),
                 FormatArgs :: list(),
                 Opts :: [Opt],
                 Opt :: {heading, string()} | no_css | esc_chars.

Prints from a test case to the log file.

This function is meant for printing a string directly from a test case to the test case log file.

Default Category is default, default Importance is ?STD_IMPORTANCE, and default value for FormatArgs is [].

For details on Category, Importance and the no_css option, see section Logging - Categories and Verbosity Levels in the User's Guide.

Common Test will not escape special HTML characters (<, > and &) in the text printed with this function, unless the esc_chars option is used.

make_priv_dir()

(since OTP R15B01)

-spec make_priv_dir() -> ok | {error, Reason} when Reason :: term().

If the test is started with option create_priv_dir set to manual_per_tc, in order for the test case to use the private directory, it must first create it by calling this function.

notify(Name, Data)

(since OTP R15B02)

-spec notify(Name, Data) -> ok when Name :: atom(), Data :: term().

Sends an asynchronous notification of type Name with Datato the Common Test event manager. This can later be caught by any installed event manager.

See also gen_event.

pal(Format)

-spec pal(Format) -> ok when Format :: string().

Equivalent to pal(default, ?STD_IMPORTANCE, Format, []).

pal(X1, X2)

-spec pal(X1, X2) -> ok
             when
                 X1 :: Category | Importance | Format,
                 X2 :: Format | FormatArgs,
                 Category :: atom() | integer() | string(),
                 Importance :: integer(),
                 Format :: string(),
                 FormatArgs :: list().

Equivalent to pal(Category, Importance, Format, FormatArgs, []).

pal(X1, X2, X3)

-spec pal(X1, X2, X3) -> ok
             when
                 X1 :: Category | Importance,
                 X2 :: Importance | Format,
                 X3 :: Format | FormatArgs | Opt,
                 Category :: atom() | integer() | string(),
                 Importance :: integer(),
                 Format :: string(),
                 FormatArgs :: list(),
                 Opt :: {heading, string()} | no_css.

Equivalent to pal(Category, Importance, Format, FormatArgs, Opts).

pal(X1, X2, X3, X4)

(since OTP R15B02)

-spec pal(X1, X2, X3, X4) -> ok
             when
                 X1 :: Category | Importance,
                 X2 :: Importance | Format,
                 X3 :: Format | FormatArgs,
                 X4 :: FormatArgs | Opts,
                 Category :: atom() | integer() | string(),
                 Importance :: integer(),
                 Format :: string(),
                 FormatArgs :: list(),
                 Opts :: [Opt],
                 Opt :: {heading, string()} | no_css.

Equivalent to pal(Category, Importance, Format, FormatArgs, Opts).

pal(Category, Importance, Format, FormatArgs, Opts)

(since OTP 19.2)

-spec pal(Category, Importance, Format, FormatArgs, Opts) -> ok
             when
                 Category :: atom() | integer() | string(),
                 Importance :: integer(),
                 Format :: string(),
                 FormatArgs :: list(),
                 Opts :: [Opt],
                 Opt :: {heading, string()} | no_css.

Prints and logs from a test case.

This function is meant for printing a string from a test case, both to the test case log file and to the console.

Default Category is default, default Importance is ?STD_IMPORTANCE, and default value for FormatArgs is [].

For details on Category and Importance, see section Logging - Categories and Verbosity Levels in the User's Guide.

Note that special characters in the text (<, > and &) will be escaped by Common Test before the text is printed to the log file.

parse_table(Data)

-spec parse_table(Data) -> {Heading, Table}
                     when Data :: [string()], Heading :: tuple(), Table :: [tuple()].

Parses the printout from an SQL table and returns a list of tuples.

The printout to parse is typically the result of a select command in SQL. The returned Table is a list of tuples, where each tuple is a row in the table.

Heading is a tuple of strings representing the headings of each column in the table.

print(Format)

-spec print(Format) -> ok when Format :: string().

Equivalent to print(default, ?STD_IMPORTANCE, Format, [], []).

print(X1, X2)

(since OTP R15B02)

-spec print(X1, X2) -> ok
               when
                   X1 :: Category | Importance | Format,
                   X2 :: Format | FormatArgs,
                   Category :: atom() | integer() | string(),
                   Importance :: integer(),
                   Format :: string(),
                   FormatArgs :: list().

Equivalent to print(Category, Importance, Format, FormatArgs, []).

print(X1, X2, X3)

-spec print(X1, X2, X3) -> ok
               when
                   X1 :: Category | Importance,
                   X2 :: Importance | Format,
                   X3 :: Format | FormatArgs | Opts,
                   Category :: atom() | integer() | string(),
                   Importance :: integer(),
                   Format :: string(),
                   FormatArgs :: list(),
                   Opts :: [Opt],
                   Opt :: {heading, string()}.

Equivalent to print(Category, Importance, Format, FormatArgs, Opts).

print(X1, X2, X3, X4)

(since OTP R15B02)

-spec print(X1, X2, X3, X4) -> ok
               when
                   X1 :: Category | Importance,
                   X2 :: Importance | Format,
                   X3 :: Format | FormatArgs,
                   X4 :: FormatArgs | Opts,
                   Category :: atom() | integer() | string(),
                   Importance :: integer(),
                   Format :: string(),
                   FormatArgs :: list(),
                   Opts :: [Opt],
                   Opt :: {heading, string()}.

Equivalent to print(Category, Importance, Format, FormatArgs, Opts).

print(Category, Importance, Format, FormatArgs, Opts)

(since OTP 19.2)

-spec print(Category, Importance, Format, FormatArgs, Opts) -> ok
               when
                   Category :: atom() | integer() | string(),
                   Importance :: integer(),
                   Format :: string(),
                   FormatArgs :: list(),
                   Opts :: [Opt],
                   Opt :: {heading, string()}.

Prints from a test case to the console.

This function is meant for printing a string from a test case to the console.

Default Category is default, default Importance is ?STD_IMPORTANCE, and default value for FormatArgs is [].

For details on Category and Importance, see section Logging - Categories and Verbosity Levels in the User's Guide.

reload_config(Required)

(since OTP R14B)

-spec reload_config(Required) -> ValueOrElement | {error, Reason}
                       when
                           Required :: KeyOrName | {KeyOrName, SubKey} | {KeyOrName, SubKey, SubKey},
                           KeyOrName :: key_or_name(),
                           SubKey :: atom(),
                           ValueOrElement :: term(),
                           Reason :: term().

Reloads configuration file containing specified configuration key.

This function updates the configuration data from which the specified configuration variable was read, and returns the (possibly) new value of this variable.

If some variables were present in the configuration, but are not loaded using this function, they are removed from the configuration table together with their aliases.

remaining_test_procs()

(since OTP 20.2)

-spec remaining_test_procs() -> {TestProcs, SharedGL, OtherGLs}
                              when
                                  TestProcs :: [{pid(), GL}],
                                  GL :: pid(),
                                  SharedGL :: pid(),
                                  OtherGLs :: [pid()].

This function will return the identity of test- and group leader processes that are still running at the time of this call. TestProcs are processes in the system that have a Common Test IO process as group leader. SharedGL is the central Common Test IO process, responsible for printing to log files for configuration functions and sequentially executing test cases. OtherGLs are Common Test IO processes that print to log files for test cases in parallel test case groups.

The process information returned by this function may be used to locate and terminate remaining processes after tests have finished executing. The function would typically by called from Common Test Hook functions.

Note that processes that execute configuration functions or test cases are never included in TestProcs. It is therefore safe to use post configuration hook functions (such as post_end_per_suite, post_end_per_group, post_end_per_testcase) to terminate all processes in TestProcs that have the current group leader process as its group leader.

Note also that the shared group leader (SharedGL) must never be terminated by the user, only by Common Test. Group leader processes for parallel test case groups (OtherGLs) may however be terminated in post_end_per_group hook functions.

remove_config(Callback, Config)

(since OTP R14B)

-spec remove_config(Callback, Config) -> ok when Callback :: atom(), Config :: string().

Removes configuration variables (together with their aliases) that were loaded with specified callback module and configuration string.

require(Required)

-spec require(Required) -> ok | {error, Reason}
                 when
                     Required :: Key | {Key, SubKeys} | {Key, SubKey, SubKeys},
                     Key :: atom(),
                     SubKeys :: SubKey | [SubKey],
                     SubKey :: atom(),
                     Reason :: term().

Checks if the required configuration is available. Arbitrarily deep tuples can be specified as Required. Only the last element of the tuple can be a list of SubKeys.

Example 1. Require the variable myvar:

ok = ct:require(myvar).

In this case the configuration file must at least contain:

{myvar,Value}.

Example 2. Require key myvar with subkeys sub1 and sub2:

ok = ct:require({myvar,[sub1,sub2]}).

In this case the configuration file must at least contain:

{myvar,[{sub1,Value},{sub2,Value}]}.

Example 3. Require key myvar with subkey sub1 with subsub1:

ok = ct:require({myvar,sub1,sub2}).

In this case the configuration file must at least contain:

{myvar,[{sub1,[{sub2,Value}]}]}.

See also ct:get_config/1, ct:get_config/2, ct:get_config/3, ct:require/2.

require(Name, Required)

-spec require(Name, Required) -> ok | {error, Reason}
                 when
                     Name :: atom(),
                     Required :: Key | {Key, SubKey} | {Key, SubKey, SubKey},
                     SubKey :: Key,
                     Key :: atom(),
                     Reason :: term().

Checks if the required configuration is available and gives it a name. The semantics for Required is the same as in ct:require/1 except that a list of SubKeys cannot be specified.

If the requested data is available, the subentry is associated with Name so that the value of the element can be read with ct:get_config/1,2 provided Name is used instead of the whole Required term.

Example:

Require one node with a Telnet connection and an FTP connection. Name the node a:

ok = ct:require(a,{machine,node}).

All references to this node can then use the node name. For example, a file over FTP is fetched like follows:

ok = ct:ftp_get(a,RemoteFile,LocalFile).

For this to work, the configuration file must at least contain:

{machine,[{node,[{telnet,IpAddr},{ftp,IpAddr}]}]}.

Note

The behavior of this function changed radically in Common Test 1.6.2. To keep some backwards compatibility, it is still possible to do: ct:require(a,{node,[telnet,ftp]}). This associates the name a with the top-level node entry. For this to work, the configuration file must at least contain: {node,[{telnet,IpAddr},{ftp,IpAddr}]}.

See also ct:get_config/1, ct:get_config/2, ct:get_config/3, ct:require/1.

run(TestDirs)

-spec run(TestDirs) -> Result
             when
                 TestDirs :: TestDir | [TestDir],
                 TestDir :: string(),
                 Result :: [TestResult] | {error, Reason},
                 TestResult :: term(),
                 Reason :: term().

Runs all test cases in all suites in the specified directories.

See also ct:run/3.

run(TestDir, Suite)

-spec run(TestDir, Suite) -> Result
             when
                 TestDir :: string(),
                 Suite :: atom(),
                 Result :: [TestResult] | {error, Reason},
                 TestResult :: term(),
                 Reason :: term().

Runs all test cases in the specified suite.

See also ct:run/3.

run(TestDir, Suite, Cases)

-spec run(TestDir, Suite, Cases) -> Result
             when
                 TestDir :: string(),
                 Suite :: atom(),
                 Cases :: atom() | [atom()],
                 Result :: [TestResult] | {error, Reason},
                 TestResult :: term(),
                 Reason :: term().

Runs the specified test cases.

Requires that ct:install/1 has been run first.

Suites (*_SUITE.erl) files must be stored in TestDir or TestDir/test. All suites are compiled when the test is run.

run_test(Opts)

-spec run_test(Opts) -> Result
                  when
                      Opts :: [OptTuples],
                      OptTuples ::
                          {dir, TestDirs} |
                          {suite, Suites} |
                          {group, Groups} |
                          {testcase, Cases} |
                          {spec, TestSpecs} |
                          {join_specs, boolean()} |
                          {label, Label} |
                          {config, CfgFiles} |
                          {userconfig, UserConfig} |
                          {allow_user_terms, boolean()} |
                          {logdir, LogDir} |
                          {silent_connections, Conns} |
                          {stylesheet, CSSFile} |
                          {cover, CoverSpecFile} |
                          {cover_stop, boolean()} |
                          {step, StepOpts} |
                          {event_handler, EventHandlers} |
                          {include, InclDirs} |
                          {auto_compile, boolean()} |
                          {abort_if_missing_suites, boolean()} |
                          {create_priv_dir, CreatePrivDir} |
                          {multiply_timetraps, M} |
                          {scale_timetraps, boolean()} |
                          {repeat, N} |
                          {duration, DurTime} |
                          {until, StopTime} |
                          {force_stop, ForceStop} |
                          {decrypt, DecryptKeyOrFile} |
                          {refresh_logs, LogDir} |
                          {logopts, LogOpts} |
                          {verbosity, VLevels} |
                          {basic_html, boolean()} |
                          {esc_chars, boolean()} |
                          {keep_logs, KeepSpec} |
                          {ct_hooks, CTHs} |
                          {ct_hooks_order, CTHsOrder} |
                          {enable_builtin_hooks, boolean()} |
                          {release_shell, boolean()},
                      TestDirs :: [string()] | string(),
                      Suites :: [string()] | [atom()] | string() | atom(),
                      Cases :: [atom()] | atom(),
                      Groups :: GroupNameOrPath | [GroupNameOrPath],
                      GroupNameOrPath :: [atom()] | atom() | all,
                      TestSpecs :: [string()] | string(),
                      Label :: string() | atom(),
                      CfgFiles :: [string()] | string(),
                      UserConfig :: [{CallbackMod, CfgStrings}] | {CallbackMod, CfgStrings},
                      CallbackMod :: atom(),
                      CfgStrings :: [string()] | string(),
                      LogDir :: string(),
                      Conns :: all | [atom()],
                      CSSFile :: string(),
                      CoverSpecFile :: string(),
                      StepOpts :: [StepOpt],
                      StepOpt :: config | keep_inactive,
                      EventHandlers :: EH | [EH],
                      EH :: atom() | {atom(), InitArgs} | {[atom()], InitArgs},
                      InitArgs :: [term()],
                      InclDirs :: [string()] | string(),
                      CreatePrivDir :: auto_per_run | auto_per_tc | manual_per_tc,
                      M :: integer(),
                      N :: integer(),
                      DurTime :: HHMMSS,
                      HHMMSS :: string(),
                      StopTime :: YYMoMoDDHHMMSS | HHMMSS,
                      YYMoMoDDHHMMSS :: string(),
                      ForceStop :: skip_rest | boolean(),
                      DecryptKeyOrFile :: {key, DecryptKey} | {file, DecryptFile},
                      DecryptKey :: string(),
                      DecryptFile :: string(),
                      LogOpts :: [LogOpt],
                      LogOpt :: no_nl | no_src,
                      VLevels :: VLevel | [{Category, VLevel}],
                      VLevel :: integer(),
                      Category :: atom(),
                      KeepSpec :: all | pos_integer(),
                      CTHs :: [CTHModule | {CTHModule, CTHInitArgs}],
                      CTHsOrder :: atom(),
                      CTHModule :: atom(),
                      CTHInitArgs :: term(),
                      Result ::
                          {Ok, Failed, {UserSkipped, AutoSkipped}} | TestRunnerPid | {error, Reason},
                      Ok :: integer(),
                      Failed :: integer(),
                      UserSkipped :: integer(),
                      AutoSkipped :: integer(),
                      TestRunnerPid :: pid(),
                      Reason :: term().

Runs tests as specified by the combination of options in Opts. The options are the same as those used with program ct_run, see Run Tests from Command Line in the ct_run manual page.

Here a TestDir can be used to point out the path to a Suite. Option testcase corresponds to option -case in program ct_run. Configuration files specified in Opts are installed automatically at startup.

TestRunnerPid is returned if release_shell == true. For details, see ct:break/1.

Reason indicates the type of error encountered.

run_testspec(TestSpec)

-spec run_testspec(TestSpec) -> Result
                      when
                          TestSpec :: [term()],
                          Result :: {Ok, Failed, {UserSkipped, AutoSkipped}} | {error, Reason},
                          Ok :: integer(),
                          Failed :: integer(),
                          UserSkipped :: integer(),
                          AutoSkipped :: integer(),
                          Reason :: term().

Runs a test specified by TestSpec. The same terms are used as in test specification files.

Reason indicates the type of error encountered.

set_verbosity(Category, Level)

(since OTP 19.1)

-spec set_verbosity(Category, Level) -> ok when Category :: default | atom(), Level :: integer().

Use this function to set, or modify, the verbosity level for a logging category. See the User's Guide for details. Use the value default to set the general verbosity level.

sleep(Time)

(since OTP R14B)

-spec sleep(Time) -> ok
               when
                   Time :: {hours, Hours} | {minutes, Mins} | {seconds, Secs} | Millisecs,
                   Hours :: integer(),
                   Mins :: integer(),
                   Secs :: integer(),
                   Millisecs :: timeout() | float().

This function, similar to timer:sleep/1 in STDLIB, suspends the test case for a specified time. However, this function also multiplies Time with the multiply_timetraps value (if set) and under certain circumstances also scales up the time automatically if scale_timetraps is set to true (default is false).

start_interactive()

-spec start_interactive() -> ok.

Starts Common Test in interactive mode.

From this mode, all test case support functions can be executed directly from the Erlang shell. The interactive mode can also be started from the OS command line with ct_run -shell [-config File...].

If any functions (for example, Telnet or FTP) using "required configuration data" are to be called from the Erlang shell, configuration data must first be required with ct:require/2.

Example:

> ct:require(unix_telnet, unix).
ok
> ct_telnet:open(unix_telnet).
{ok,<0.105.0>}
> ct_telnet:cmd(unix_telnet, "ls .").
{ok,["ls","file1  ...",...]}

step(TestDir, Suite, Case)

-spec step(TestDir, Suite, Case) -> Result
              when TestDir :: string(), Suite :: atom(), Case :: atom(), Result :: term().

Steps through a test case with the debugger.

See also ct:run/3.

step(TestDir, Suite, Case, Opts)

-spec step(TestDir, Suite, Case, Opts) -> Result
              when
                  TestDir :: string(),
                  Suite :: atom(),
                  Case :: atom(),
                  Opts :: [Opt],
                  Opt :: config | keep_inactive,
                  Result :: term().

Steps through a test case with the debugger. If option config has been specified, breakpoints are also set on the configuration functions in Suite.

See also ct:run/3.

stop_interactive()

-spec stop_interactive() -> ok.

Exits the interactive mode.

See also ct:start_interactive/0.

sync_notify(Name, Data)

(since OTP R15B02)

-spec sync_notify(Name, Data) -> ok when Name :: atom(), Data :: term().

Sends a synchronous notification of type Name with Data to the Common Test event manager. This can later be caught by any installed event manager.

See also gen_event.

testcases(TestDir, Suite)

-spec testcases(TestDir, Suite) -> Testcases | {error, Reason}
                   when TestDir :: string(), Suite :: atom(), Testcases :: list(), Reason :: term().

Returns all test cases in the specified suite.

timetrap(Time)

(since OTP R14B)

-spec timetrap(Time) -> infinity | pid()
                  when
                      Time :: {hours, Hours} | {minutes, Mins} | {seconds, Secs} | timeout() | Func,
                      Hours :: integer(),
                      Mins :: integer(),
                      Secs :: integer(),
                      Func :: {M, F, A} | function(),
                      M :: atom(),
                      F :: atom(),
                      A :: list().

Sets a new timetrap for the running test case.

If the argument is Func, the timetrap is triggered when this function returns. Func can also return a new Time value, which in that case is the value for the new timetrap.

userdata(TestDir, Suite)

-spec userdata(TestDir, Suite) -> SuiteUserData | {error, Reason}
                  when TestDir :: string(), Suite :: atom(), SuiteUserData :: [term()], Reason :: term().

Returns any data specified with tag userdata in the list of tuples returned from suite/0.

userdata(TestDir, Suite, Case)

-spec userdata(TestDir, Suite, Case :: GroupOrCase) -> TCUserData | {error, Reason}
                  when
                      TestDir :: string(),
                      Suite :: atom(),
                      GroupOrCase :: {group, GroupName} | atom(),
                      GroupName :: atom(),
                      TCUserData :: [term()],
                      Reason :: term().

Returns any data specified with tag userdata in the list of tuples returned from Suite:group(GroupName) or Suite:Case().

ct_cover

Common Test framework code coverage support module.

This module exports help functions for performing code coverage analysis.

Summary

Functions

add_nodes(Nodes)

Adds nodes to current cover test. Notice that this only works if cover support is active.

cross_cover_analyse(Level, Tests)

Accumulates cover results over multiple tests. See section Cross Cover Analysis in the User's Guide.

remove_nodes(Nodes)

Removes nodes from the current cover test.

Functions

add_nodes(Nodes)

-spec add_nodes(Nodes) -> {ok, StartedNodes} | {error, Reason}
                   when
                       Nodes :: node() | [node()],
                       StartedNodes :: [node()],
                       Reason :: cover_not_running | term().

Adds nodes to current cover test. Notice that this only works if cover support is active.

To have effect, this function is to be called from init_per_suite/1 (see ct_suite) before any tests are performed.

cross_cover_analyse(Level, Tests)

(since OTP R16B)

-spec cross_cover_analyse(Level, Tests) -> ok
                             when
                                 Level :: overview | details,
                                 Tests :: [{Tag :: atom(), Dir :: file:name_all()}].

Accumulates cover results over multiple tests. See section Cross Cover Analysis in the User's Guide.

remove_nodes(Nodes)

-spec remove_nodes(Nodes) -> ok | {error, Reason}
                      when
                          Nodes :: node() | [node()],
                          Reason :: cover_not_running | not_main_node | term().

Removes nodes from the current cover test.

Call this function to stop cover test on nodes previously added with ct_cover:add_nodes/1. Results on the remote node are transferred to the Common Test node.

ct_doctest

ct_doctest runs doctests on documentation examples. Using ct_doctest ensures that the examples in the documentation are correct, up to date, and stylistically consistent.

The tested examples can be either in a module (normally written using documentation attributes) or in files. By default ct_doctest looks for markdown code blocks and runs any Erlang code block found that looks like a shell session.

The doctest parser looks for examples that are formatted as if they were run in the Erlang shell, using prompts of the form N>, where N starts at 1 for each block. The expected output is written on the lines following the prompt. For example:

-doc """
This is an example of a doctest:

```
1> 1+2.
3
```
""".

ct_doctest can be used in Common Test suites to validate documentation examples as part of your test runs. Normal usage is to call module/1 with a module name. For example:

all() ->
    [doctests].
doctests(_Config) ->
    ct_doctest:module(my_module).

Prompt format rules

For a code block to run as a doctest:

prompts must start at 1> for each block

each subsequent prompt must increment (2>, 3>, ...)

continuation lines must be indented

% style comment lines are allowed in prompt blocks

mismatched prompt numbering causes a doctest parse error

Troubleshooting

If a doctest fails unexpectedly:

use verbose to print per-block execution details

verify that expected output matches the shell output exactly

verify prompt numbering and continuation-line indentation

Examples

Below are examples of supported formats for the code blocks in the documentation. The parser is quite flexible and supports various styles, including multi-line expressions, comments, and even prebound variables.

Basic example

1> 1+2.
3

Basic example using Erlang code

This example uses an explicit Erlang code block. That is,

```erlang
1> 1+2.
3
```

instead of the previous one which is a generic code block. Both formats are supported.

1> 1+2.
3

Multi-line prompt

Use multiline prompts for expressions that span multiple lines by starting the prompt with > and indenting the continuation lines. For example:

1> 1
  +
  2
  .
3

Multi-line with comma

It is possible to have multiple expressions in the same prompt, separated by commas. For example:

1> A = 1,
  A + 2.
3

Multi-line match

The expected output can span multiple lines. For example:

1> [1, 2].
[
 1
 ,
 2
 ]

Multiple prompts

Examples can have multiple prompts. For example:

1> 1 + 2.
3
2> 3 + 4.
7

Defining variables

Any variable defined in the examples will be available in the following prompts. For example:

1> A = 1 + 2.
3
2> A + 3.
6

Prebound variables

If the documentation examples rely on certain variables being prebound, you can provide these bindings when calling module/3. For example, if you have a module doc that uses a variable Prebound, you can set it up like this:

1> Prebound.
hello

and then in your test suite:

binding_test(_Config) ->
    Bindings = [{moduledoc, #{'Prebound' => hello}}],
    ct_doctest:module(my_module, Bindings, []).

Ignore result

To ignore the results of a prompt, just skip writing the expected output. For example:

1> 1 + 2.
2> 3 + 4.
7

Matching exceptions

Examples of failures can be tested by writing the expected exception after the prompt. For example:

1> hello + 1.
** exception error: an error occurred when evaluating an arithmetic expression
     in operator  +/2
        called as hello + 1
2> lists:last([]).
** exception error: no function clause matching lists:last([])

The simplest way to know what output to write is to run the example in the shell and copy the output, including the ** exception line.

If you don't want to include the entire exception message, use only the start of the message.

1> hello + 1.
** exception error

Comments

Comments can be inserted anywhere in the code block. For example:

%% A comment before the first prompt
1> [1,
%% A comment between prompts
  2].
[1,
%% A comment in a match
 2]
2> [1,
  %% Indented comment between prompts
  2].
[1,
 %% Indented comment in a match
 2]
3> """
  %% A comment in a string is not a comment

  """.
"""
%% A comment in a string is not a comment

"""
4> 1 + a.
** exception error: an error occurred when evaluating an arithmetic expression
%% Comments
     in operator  +/2
     %% in exceptions
        called as 1 + a
%% are ignored

Matching of maps

When matching on maps, it is possible to use shell syntax, that is, => and not :=, as in normal Erlang code. For example:

1> #{ a => b }.
#{ a => b }

Matching of ...

It is possible to use ... in the expected output to indicate that the rest of the output should be ignored. This is useful for outputs that are large or contain non-deterministic elements.

1> lists:seq(1,100).
[1, 2, 3, ...]
2> #{ a => b }.
#{ a => ... }
3> <<1, 0:1024>>.
<<1, 0, 0, 0, ...>>

Compiling modules

ct_doctest can also compile full module code examples. It then looks for a -module declaration to determine the module name and compiles the code as if it were in a file. For example:

-module(my_module).
-export([foo/0]).
foo() ->
    ok.

The module is then available for use in following prompts. For example:

1> my_module:foo().

Edge cases

The following are examples that are not supported by the parser and will be ignored.

a> should not be tested

 1> should not be tested

> should not be tested

should not be tested
1>

Summary

Types

options()

Options for doctest execution.

Functions

file(File)

Equivalent to file(File, [], []).

file(File, Options)

Equivalent to file(File, [], Options).

file(File, Bindings, Options)

Run doctests for a markdown file.

module(Module)

Equivalent to module(Module, []).

module(Module, Options)

Equivalent to module(Module, [], Options).

module(Module, Bindings, Options)

Run tests for the documentation in a module with EEP-48 docs.

Types

options()

(not exported) (since OTP @OTP-20034@)

-type options() ::
          [{parser, fun((unicode:unicode_binary()) -> [unicode:unicode_binary()] | {error, term()})} |
           {skipped_blocks, non_neg_integer() | false} |
           {missing_tests, [{atom(), arity()}]} |
           {skip_tests, [moduledoc | {function | type | callback, atom(), arity()}]} |
           {verbose, boolean()}].

Options for doctest execution.

parser - Use this option to plug in an external documentation parser. The parser callback must be a fun/1 and return a list of Erlang code block binaries. The code blocks are then checked to determine whether they should be run as doctests. If no parser is provided, a built-in markdown parser will be used.

skipped_blocks - Sets the exact number of Erlang code blocks that are allowed to be skipped because no runnable shell prompts were found. It does not count blocks in any function listed in missing_tests. It defaults to false.

missing_tests - A list of {Function, Arity} pairs that are expected to have documentation but no doctests. When this option is set, ct_doctest will fail if any documented function lacks doctests and is not in this list (i.e., a new function was added without doctests), and also fail if a function in this list now has doctests (i.e., the list is stale and should be updated). Defaults to not checking.

skip_tests - A list of doc entries whose doctests should be skipped. Each entry is either moduledoc or a {Kind, Name, Arity} tuple where Kind is function, type, or callback. For example, [moduledoc, {function, foo, 1}] skips the moduledoc and the foo/1 function.

verbose - Print detailed information while running doctests, including each block run and skipped block details.

Functions

file(File)

(since OTP @OTP-20034@)

-spec file(file:filename()) -> ok | {error, term()} | no_return().

Equivalent to file(File, [], []).

file(File, Options)

(since OTP @OTP-20034@)

-spec file(file:filename(), options()) -> ok | {comment, string()} | {error, term()} | no_return().

Equivalent to file(File, [], Options).

file(File, Bindings, Options)

(since OTP @OTP-20034@)

-spec file(File :: file:filename(), Bindings :: [{atom(), term()}], Options :: options()) ->
              ok | {comment, string()} | {error, term()} | no_return().

Run doctests for a markdown file.

The function returns ok if all tests pass. If any test fails, an exception in the form of error({N, errors}) is raised, where N is the number of failed tests. The details of each failure are printed to the console.

Use Bindings to provide prebound variables. Bindings are global for all files, so take care to avoid any naming conflicts.

You can run doctests on non-markdown files by providing a custom parser that extracts the code blocks to be tested.

See options/0 for available options.

module(Module)

(since OTP @OTP-20034@)

-spec module(module()) -> ok | {comment, string()} | {error, term()} | no_return().

Equivalent to module(Module, []).

module(Module, Options)

(since OTP @OTP-20034@)

-spec module(module(), options()) -> ok | {comment, string()} | {error, term()} | no_return().

Equivalent to module(Module, [], Options).

module(Module, Bindings, Options)

(since OTP @OTP-20034@)

-spec module(Module :: module(), Bindings, Options :: options()) ->
                ok | {comment, string()} | {error, term()} | no_return()
                when
                    KFA :: {Kind :: function | type | callback, atom(), arity()},
                    Bindings :: [{KFA | moduledoc, erl_eval:binding_struct()}].

Run tests for the documentation in a module with EEP-48 docs.

When calling module/3, ct_doctest looks for documentation in the specified module and runs any examples found there. The module, function, type, and callback documentation are all checked for examples.

The function returns ok if all tests pass, or {comment, Comment} if all tests pass but one or more functions lack tests. If any test fails, an exception in the form of error({N, errors}) is raised, where N is the number of failed tests. The details of each failure are printed to the console.

Use Bindings to provide prebound variables for a specific doc entry. Use moduledoc for module docs and {function, Name, Arity} (or corresponding type/callback keys) for entry-specific bindings.

See options/0 for available options.

ct_ftp

FTP client module (based on the ftp application).

Summary

Types

connection()

Reference to opened FTP connection associated to either a handle or target_name.

handle()

Handle for a specific FTP connection, see module ct.

Functions

cd(Connection, Dir) deprecated

Changes directory on remote host.

close(Connection) deprecated

Closes the FTP connection.

delete(Connection, File) deprecated

Deletes a file on remote host.

get(KeyOrName, RemoteFile, LocalFile) deprecated

Opens an FTP connection and fetches a file from the remote host.

ls(Connection, Dir) deprecated

Lists directory Dir.

open(KeyOrName) deprecated

Opens an FTP connection to the specified node.

put(KeyOrName, LocalFile, RemoteFile) deprecated

Opens an FTP connection and sends a file to the remote host.

recv(Connection, RemoteFile) deprecated

Fetches a file over FTP.

recv(Connection, RemoteFile, LocalFile) deprecated

Fetches a file over FTP.

send(Connection, LocalFile) deprecated

Sends a file over FTP.

send(Connection, LocalFile, RemoteFile) deprecated

Sends a file over FTP.

type(Connection, Type) deprecated

Changes the file transfer type.

Types

connection()

-type connection() :: handle() | ct:target_name().

Reference to opened FTP connection associated to either a handle or target_name.

handle()

-type handle() :: ct:handle().

Handle for a specific FTP connection, see module ct.

Functions

cd(Connection, Dir)

This function is deprecated. ct_ftp:cd/2 is deprecated; Legacy protocol support will be dropped in OTP-30.

-spec cd(Connection, Dir) -> ok | {error, Reason}
            when Connection :: connection(), Dir :: file:filename(), Reason :: term().

Changes directory on remote host.

close(Connection)

This function is deprecated. ct_ftp:close/1 is deprecated; Legacy protocol support will be dropped in OTP-30.

-spec close(Connection) -> ok | {error, Reason} when Connection :: connection(), Reason :: term().

Closes the FTP connection.

delete(Connection, File)

This function is deprecated. ct_ftp:delete/2 is deprecated; Legacy protocol support will be dropped in OTP-30.

-spec delete(Connection, File) -> ok | {error, Reason}
                when Connection :: connection(), File :: file:filename(), Reason :: term().

Deletes a file on remote host.

get(KeyOrName, RemoteFile, LocalFile)

This function is deprecated. ct_ftp:get/3 is deprecated; Legacy protocol support will be dropped in OTP-30.

-spec get(KeyOrName, RemoteFile, LocalFile) -> ok | {error, Reason}
             when
                 KeyOrName :: ct:key_or_name(),
                 RemoteFile :: file:filename(),
                 LocalFile :: file:filename(),
                 Reason :: term().

Opens an FTP connection and fetches a file from the remote host.

RemoteFile and LocalFile must be absolute paths.

The configuration file must be as for ct_ftp:put/3.

See also ct:require/2.

ls(Connection, Dir)

This function is deprecated. ct_ftp:ls/2 is deprecated; Legacy protocol support will be dropped in OTP-30.

-spec ls(Connection, Dir) -> {ok, Listing} | {error, Reason}
            when
                Connection :: connection(),
                Dir :: file:filename(),
                Listing :: string(),
                Reason :: term().

Lists directory Dir.

open(KeyOrName)

This function is deprecated. ct_ftp:open/1 is deprecated; Legacy protocol support will be dropped in OTP-30.

-spec open(KeyOrName) -> {ok, Handle} | {error, Reason}
              when KeyOrName :: ct:key_or_name(), Handle :: handle(), Reason :: term().

Opens an FTP connection to the specified node.

You can open a connection for a particular Name and use the same name as reference for all following subsequent operations. If you want the connection to be associated with Handle instead (if you, for example, need to open multiple connections to a host), use Key, the configuration variable name, to specify the target. A connection without an associated target name can only be closed with the handle value.

For information on how to create a new Name, see ct:require/2.

put(KeyOrName, LocalFile, RemoteFile)

This function is deprecated. ct_ftp:put/3 is deprecated; Legacy protocol support will be dropped in OTP-30.

-spec put(KeyOrName, LocalFile, RemoteFile) -> ok | {error, Reason}
             when
                 KeyOrName :: ct:key_or_name(),
                 LocalFile :: file:filename(),
                 RemoteFile :: file:filename(),
                 Reason :: term().

Opens an FTP connection and sends a file to the remote host.

LocalFile and RemoteFile must be absolute paths.

If the target host is a "special" node, the FTP address must be specified in the configuration file as follows:

{node,[{ftp,IpAddr}]}.

If the target host is something else, for example, a UNIX host, the configuration file must also include the username and password (both strings):

{unix,[{ftp,IpAddr},
       {username,Username},
       {password,Password}]}.

See also ct:require/2.

recv(Connection, RemoteFile)

This function is deprecated. ct_ftp:recv/2 is deprecated; Legacy protocol support will be dropped in OTP-30.

-spec recv(Connection, RemoteFile) -> ok | {error, Reason}
              when Connection :: connection(), RemoteFile :: file:filename(), Reason :: term().

Fetches a file over FTP.

The file gets the same name on the local host.

See also ct_ftp:recv/3.

recv(Connection, RemoteFile, LocalFile)

This function is deprecated. ct_ftp:recv/3 is deprecated; Legacy protocol support will be dropped in OTP-30.

-spec recv(Connection, RemoteFile, LocalFile) -> ok | {error, Reason}
              when
                  Connection :: connection(),
                  RemoteFile :: file:filename(),
                  LocalFile :: file:filename(),
                  Reason :: term().

Fetches a file over FTP.

The file is named LocalFile on the local host.

send(Connection, LocalFile)

This function is deprecated. ct_ftp:send/2 is deprecated; Legacy protocol support will be dropped in OTP-30.

-spec send(Connection, LocalFile) -> ok | {error, Reason}
              when Connection :: connection(), LocalFile :: file:filename(), Reason :: term().

Sends a file over FTP.

The file gets the same name on the remote host.

See also ct_ftp:send/3.

send(Connection, LocalFile, RemoteFile)

This function is deprecated. ct_ftp:send/3 is deprecated; Legacy protocol support will be dropped in OTP-30.

-spec send(Connection, LocalFile, RemoteFile) -> ok | {error, Reason}
              when
                  Connection :: connection(),
                  LocalFile :: file:filename(),
                  RemoteFile :: file:filename(),
                  Reason :: term().

Sends a file over FTP.

The file is named RemoteFile on the remote host.

type(Connection, Type)

This function is deprecated. ct_ftp:type/2 is deprecated; Legacy protocol support will be dropped in OTP-30.

-spec type(Connection, Type) -> ok | {error, Reason}
              when Connection :: connection(), Type :: ascii | binary, Reason :: term().

Changes the file transfer type.

ct_hooks behaviour

A callback interface on top of Common Test.

The Common Test Hook (CTH) framework allows extensions of the default behavior of Common Test by callbacks before and after all test suite calls. It is intended for advanced users of Common Test who want to abstract out behavior that is common to multiple test suites.

In brief, CTH allows you to:

Manipulate the runtime configuration before each suite configuration call.

Manipulate the return of all suite configuration calls and by extension the result of the test themselves.

The following sections describe the mandatory and optional CTH functions that Common Test calls during test execution. For more details, see section Common Test Hooks in the User's Guide.

For information about how to add a CTH to your suite, see section Installing a CTH in the User's Guide.

Note

For a minimal example of a CTH, see section Example CTH in the User's Guide.

Summary

Callbacks

id(Opts)

The Id identifies a CTH instance uniquely. If two CTHs return the same Id, the second CTH is ignored and subsequent calls to the CTH are only made to the first instance. For details, see section Installing a CTH in the User's Guide.

init(Id, Opts)

This function is always called before any other callback function. Use it to initiate any common state. It is to return a state for this CTH.

on_tc_fail(SuiteName, TestName, Reason, CTHState)

This function is called whenever a test case (or configuration function) fails. It is called after the post function is called for the failed test case.

on_tc_skip(SuiteName, TestName, Reason, CTHState)

This function is called whenever a test case (or configuration function) is skipped. It is called after the post function is called for the skipped test case.

post_all(SuiteName, Return, GroupDefs)

This function is called after all/0. It is used to modify the set of test cases and test group to be executed, for instance to add or remove test cases and groups, change group properties, or even skip all tests in the suite.

post_end_per_group(SuiteName, GroupName, Config, Return, CTHState)

This function is called after end_per_group if it exists. It behaves the same way as post_init_per_suite, but for function end_per_group instead.

post_end_per_suite(SuiteName, Config, Return, CTHState)

This function is called after end_per_suite if it exists. It behaves the same way as post_init_per_suite, but for function end_per_suite instead.

post_end_per_testcase(SuiteName, TestcaseName, Config, Return, CTHState)

This function is called after end_per_testcase if it exists. It behaves the same way as post_end_per_suite, but for function end_per_testcase instead.

post_groups(SuiteName, GroupDefs)

This function is called after groups/0. It is used to modify the test group definitions, for instance to add or remove groups or change group properties.

post_init_per_group(SuiteName, GroupName, Config, Return, CTHState)

This function is called after init_per_group if it exists. It behaves the same way as post_init_per_suite, but for function init_per_group instead.

post_init_per_suite(SuiteName, Config, Return, CTHState)

This function is called after init_per_suite if it exists. It typically contains extra checks to ensure that all the correct dependencies are started correctly.

post_init_per_testcase(SuiteName, TestcaseName, Config, Return, CTHState)

This function is called after init_per_testcase if it exists. It behaves the same way as post_init_per_suite, but for function init_per_testcase instead.

pre_end_per_group(SuiteName, GroupName, EndData, CTHState)

This function is called before end_per_group if it exists. It behaves the same way as pre_init_per_suite, but for function end_per_group instead.

pre_end_per_suite(SuiteName, EndData, CTHState)

This function is called before end_per_suite if it exists. It behaves the same way as pre_init_per_suite, but for function end_per_suite instead.

pre_end_per_testcase(SuiteName, TestcaseName, EndData, CTHState)

This function is called before end_per_testcase if it exists. It behaves the same way as pre_end_per_suite, but for function end_per_testcase instead.

pre_init_per_group(SuiteName, GroupName, InitData, CTHState)

This function is called before init_per_group if it exists. It behaves the same way as pre_init_per_suite, but for function init_per_group instead.

pre_init_per_suite(SuiteName, InitData, CTHState)

This function is called before init_per_suite if it exists. It typically contains initialization/logging that must be done before init_per_suite is called. If {skip,Reason} or {fail,Reason} is returned, init_per_suite and all test cases of the suite are skipped and Reason printed in the overview log of the suite.

pre_init_per_testcase(SuiteName, TestcaseName, InitData, CTHState)

This function is called before init_per_testcase if it exists. It behaves the same way as pre_init_per_suite, but for function init_per_testcase instead.

terminate(Hooks)

This function is called at the end of a CTH scope. The returned term is ignored.

Callbacks

id(Opts)

(since OTP R14B02) (optional)

-callback id(Opts) -> Id when Opts :: term(), Id :: term().

The Id identifies a CTH instance uniquely. If two CTHs return the same Id, the second CTH is ignored and subsequent calls to the CTH are only made to the first instance. For details, see section Installing a CTH in the User's Guide.

This function is not to have any side effects, as it can be called multiple times by Common Test.

If not implemented, the CTH acts as if this function returned a call to make_ref/0.

init(Id, Opts)

(since OTP R14B02)

-callback init(Id, Opts) -> {ok, State} | {ok, State, Priority}
                  when Id :: reference() | term(), Opts :: term(), State :: term(), Priority :: integer().

This function is always called before any other callback function. Use it to initiate any common state. It is to return a state for this CTH.

Id is either the return value of ct_hooks:id/1, or a reference (created using erlang:make_ref/0 in ERTS) if ct_hooks:id/1 is not implemented.

Priority is the relative priority of this hook. Hooks with a lower priority are executed first. If no priority is specified, it is set to 0.

For details about hook execution order, see section CTH Execution Order in the User's Guide.

For details about when init is called, see section CTH Scope in the User's Guide.

on_tc_fail(SuiteName, TestName, Reason, CTHState)

(since OTP 19.3) (optional)

-callback on_tc_fail(SuiteName, TestName, Reason, CTHState) -> NewCTHState
                        when
                            SuiteName :: atom(),
                            TestName ::
                                init_per_suite | end_per_suite |
                                {init_per_group, GroupName} |
                                {end_per_group, GroupName} |
                                {FuncName, GroupName} |
                                FuncName,
                            FuncName :: atom(),
                            GroupName :: atom(),
                            Reason :: term(),
                            CTHState :: term(),
                            NewCTHState :: term().

This function is called whenever a test case (or configuration function) fails. It is called after the post function is called for the failed test case.

That is:

If init_per_suite fails, this function is called after post_init_per_suite.

If a test case fails, this function is called after post_end_per_testcase.

If the failed test case belongs to a test case group, the second argument is a tuple {FuncName,GroupName}, otherwise only the function name.

The data that comes with Reason follows the same format as FailReason in event tc_done. For details, see section Event Handling in the User's Guide.

If Module:on_tc_fail/4 is not exported, common_test will attempt to call Module:on_tc_fail(TestName, Reason, CTHState) instead. This is for backwards compatibility.

on_tc_skip(SuiteName, TestName, Reason, CTHState)

(since OTP 19.3) (optional)

-callback on_tc_skip(SuiteName, TestName, Reason, CTHState) -> NewCTHState
                        when
                            SuiteName :: atom(),
                            TestName ::
                                init_per_suite | end_per_suite |
                                {init_per_group, GroupName} |
                                {end_per_group, GroupName} |
                                {FuncName, GroupName} |
                                FuncName,
                            FuncName :: atom(),
                            GroupName :: atom(),
                            Reason :: {tc_auto_skip | tc_user_skip, term()},
                            CTHState :: term(),
                            NewCTHState :: term().

This function is called whenever a test case (or configuration function) is skipped. It is called after the post function is called for the skipped test case.

That is:

If init_per_group is skipped, this function is called after post_init_per_group.

If a test case is skipped, this function is called after post_end_per_testcase.

If the skipped test case belongs to a test case group, the second argument is a tuple {FuncName,GroupName}, otherwise only the function name.

The data that comes with Reason follows the same format as events tc_auto_skip and tc_user_skip For details, see section Event Handling in the User's Guide.

If Module:on_tc_skip/4 is not exported, common_test will attempt to call Module:on_tc_skip(TestName, Reason, CTHState) instead. This is for backwards compatibility.

post_all(SuiteName, Return, GroupDefs)

(since OTP 21.3.8) (optional)

-callback post_all(SuiteName, Return, GroupDefs) -> NewReturn
                      when
                          SuiteName :: atom(),
                          Return :: Tests | {skip, Reason},
                          NewReturn :: Tests | {skip, Reason},
                          Tests ::
                              [TestCase |
                               {testcase, TestCase, TCRepeatProps} |
                               {group, GroupName} |
                               {group, GroupName, Properties} |
                               {group, GroupName, Properties, SubGroups}],
                          TestCase :: atom(),
                          TCRepeatProps :: [{repeat, N} | {repeat_until_ok, N} | {repeat_until_fail, N}],
                          GroupName :: atom(),
                          Properties :: GroupProperties | default,
                          SubGroups :: [{GroupName, Properties} | {GroupName, Properties, SubGroups}],
                          Shuffle :: shuffle | {shuffle, Seed},
                          Seed :: {integer(), integer(), integer()},
                          GroupRepeatType ::
                              repeat | repeat_until_all_ok | repeat_until_all_fail | repeat_until_any_ok |
                              repeat_until_any_fail,
                          N :: integer() | forever,
                          GroupDefs :: [Group],
                          Group :: {GroupName, GroupProperties, GroupsAndTestCases},
                          GroupProperties :: [parallel | sequence | Shuffle | {GroupRepeatType, N}],
                          GroupsAndTestCases :: [Group | {group, GroupName} | TestCase],
                          Reason :: term().

This function is called after all/0. It is used to modify the set of test cases and test group to be executed, for instance to add or remove test cases and groups, change group properties, or even skip all tests in the suite.

Return is what all/0 returned, that is, a list of test cases and groups to be executed, or a tuple {skip,Reason}.

GroupDefs is what groups/0 or the post_groups/2 hook returned, that is, a list of group definitions.

NewReturn is the possibly modified version of Return.

This function is called only if the CTH is added before init_per_suite is run. For details, see section CTH Scope in the User's Guide.

Notice that for CTHs that are installed by means of the suite/0 function, post_all/2 is called before the init/2 hook function. However, for CTHs that are installed by means of the CT start flag, the init/2 function is called first.

Note

Prior to each test execution, Common Test does a simulated test run in order to count test suites, groups and cases for logging purposes. This causes the post_all/3 hook function to always be called twice. For this reason, side effects are best avoided in this callback.

post_end_per_group(SuiteName, GroupName, Config, Return, CTHState)

(since OTP 19.3) (optional)

-callback post_end_per_group(SuiteName, GroupName, Config, Return, CTHState) -> Result
                                when
                                    SuiteName :: atom(),
                                    GroupName :: atom(),
                                    Config :: [{Key, Value}],
                                    Return :: Config | SkipOrFail | term(),
                                    NewReturn :: Config | SkipOrFail | term(),
                                    SkipOrFail :: {fail, Reason} | {skip, Reason},
                                    CTHState :: term(),
                                    NewCTHState :: term(),
                                    Result :: {NewReturn, NewCTHState},
                                    Key :: atom(),
                                    Value :: term(),
                                    Reason :: term().

This function is called after end_per_group if it exists. It behaves the same way as post_init_per_suite, but for function end_per_group instead.

If Module:post_end_per_group/5 is not exported, common_test will attempt to call Module:post_end_per_group(GroupName, Config, Return, CTHState) instead. This is for backwards compatibility.

post_end_per_suite(SuiteName, Config, Return, CTHState)

(since OTP R14B02) (optional)

-callback post_end_per_suite(SuiteName, Config, Return, CTHState) -> Result
                                when
                                    SuiteName :: atom(),
                                    Config :: [{Key, Value}],
                                    Return :: Config | SkipOrFail | term(),
                                    NewReturn :: Config | SkipOrFail | term(),
                                    SkipOrFail :: {fail, Reason} | {skip, Reason},
                                    CTHState :: term(),
                                    NewCTHState :: term(),
                                    Result :: {NewReturn, NewCTHState},
                                    Key :: atom(),
                                    Value :: term(),
                                    Reason :: term().

This function is called after end_per_suite if it exists. It behaves the same way as post_init_per_suite, but for function end_per_suite instead.

post_end_per_testcase(SuiteName, TestcaseName, Config, Return, CTHState)

(since OTP 19.3) (optional)

-callback post_end_per_testcase(SuiteName, TestcaseName, Config, Return, CTHState) -> Result
                                   when
                                       SuiteName :: atom(),
                                       TestcaseName :: atom(),
                                       Config :: [{Key, Value}],
                                       Return :: Config | SkipOrFail | term(),
                                       NewReturn :: Config | SkipOrFail | term(),
                                       SkipOrFail :: {fail, Reason} | {skip, Reason},
                                       CTHState :: term(),
                                       NewCTHState :: term(),
                                       Result :: {NewReturn, NewCTHState},
                                       Key :: atom(),
                                       Value :: term(),
                                       Reason :: term().

This function is called after end_per_testcase if it exists. It behaves the same way as post_end_per_suite, but for function end_per_testcase instead.

If Module:post_end_per_testcase/5 is not exported, common_test will attempt to call Module:post_end_per_testcase(TestcaseName, Config, Return, CTHState) instead. This is for backwards compatibility.

post_groups(SuiteName, GroupDefs)

(since OTP 21.3.8) (optional)

-callback post_groups(SuiteName, GroupDefs) -> NewGroupDefs
                         when
                             SuiteName :: atom(),
                             GroupDefs :: [Group],
                             NewGroupDefs :: [Group],
                             Group :: {GroupName, Properties, GroupsAndTestCases},
                             GroupName :: atom(),
                             Properties :: [parallel | sequence | Shuffle | {GroupRepeatType, N}],
                             GroupsAndTestCases ::
                                 [Group |
                                  {group, GroupName} |
                                  TestCase |
                                  {testcase, TestCase, TCRepeatProps}],
                             TestCase :: atom(),
                             TCRepeatProps :: [{repeat, N} | {repeat_until_ok, N} | {repeat_until_fail, N}],
                             Shuffle :: shuffle | {shuffle, Seed},
                             Seed :: {integer(), integer(), integer()},
                             GroupRepeatType ::
                                 repeat | repeat_until_all_ok | repeat_until_all_fail |
                                 repeat_until_any_ok | repeat_until_any_fail,
                             N :: integer() | forever.

This function is called after groups/0. It is used to modify the test group definitions, for instance to add or remove groups or change group properties.

GroupDefs is what groups/0 returned, that is, a list of group definitions.

NewGroupDefs is the possibly modified version of this list.

This function is called only if the CTH is added before init_per_suite is run. For details, see section CTH Scope in the User's Guide.

Notice that for CTHs that are installed by means of the suite/0 function, post_groups/2 is called before the init/2 hook function. However, for CTHs that are installed by means of the CT start flag, the init/2 function is called first.

Note

Prior to each test execution, Common Test does a simulated test run in order to count test suites, groups and cases for logging purposes. This causes the post_groups/2 hook function to always be called twice. For this reason, side effects are best avoided in this callback.

post_init_per_group(SuiteName, GroupName, Config, Return, CTHState)

(since OTP 19.3) (optional)

-callback post_init_per_group(SuiteName, GroupName, Config, Return, CTHState) -> Result
                                 when
                                     SuiteName :: atom(),
                                     GroupName :: atom(),
                                     Config :: [{Key, Value}],
                                     Return :: Config | SkipOrFail | term(),
                                     NewReturn :: Config | SkipOrFail | term(),
                                     SkipOrFail :: {fail, Reason} | {skip, Reason},
                                     CTHState :: term(),
                                     NewCTHState :: term(),
                                     Result :: {NewReturn, NewCTHState},
                                     Key :: atom(),
                                     Value :: term(),
                                     Reason :: term().

This function is called after init_per_group if it exists. It behaves the same way as post_init_per_suite, but for function init_per_group instead.

If Module:post_init_per_group/5 is not exported, common_test will attempt to call Module:post_init_per_group(GroupName, Config, Return, CTHState) instead. This is for backwards compatibility.

post_init_per_suite(SuiteName, Config, Return, CTHState)

(since OTP R14B02) (optional)

-callback post_init_per_suite(SuiteName, Config, Return, CTHState) -> Result
                                 when
                                     SuiteName :: atom(),
                                     Config :: [{Key, Value}],
                                     Return :: Config | SkipOrFail | term(),
                                     NewReturn :: Config | SkipOrFail | term(),
                                     SkipOrFail :: {fail, Reason} | {skip, Reason} | term(),
                                     CTHState :: term(),
                                     NewCTHState :: term(),
                                     Result :: {NewReturn, NewCTHState},
                                     Key :: atom(),
                                     Value :: term(),
                                     Reason :: term().

This function is called after init_per_suite if it exists. It typically contains extra checks to ensure that all the correct dependencies are started correctly.

Return is what init_per_suite returned, that is, {fail,Reason}, {skip,Reason}, a Config list, or a term describing how init_per_suite failed.

NewReturn is the possibly modified return value of init_per_suite. To recover from a failure in init_per_suite, return ConfigList with the tc_status element removed. For more details, see Post Hooks in section "Manipulating Tests" in the User's Guide.

CTHState is the current internal state of the CTH.

This function is called only if the CTH is added before or in init_per_suite. For details, see section CTH Scope in the User's Guide.

post_init_per_testcase(SuiteName, TestcaseName, Config, Return, CTHState)

(since OTP 19.3) (optional)

-callback post_init_per_testcase(SuiteName, TestcaseName, Config, Return, CTHState) -> Result
                                    when
                                        SuiteName :: atom(),
                                        TestcaseName :: atom(),
                                        Config :: [{Key, Value}],
                                        Return :: Config | SkipOrFail | term(),
                                        NewReturn :: Config | SkipOrFail | term(),
                                        SkipOrFail :: {fail, Reason} | {skip, Reason},
                                        CTHState :: term(),
                                        NewCTHState :: term(),
                                        Result :: {NewReturn, NewCTHState},
                                        Key :: atom(),
                                        Value :: term(),
                                        Reason :: term().

This function is called after init_per_testcase if it exists. It behaves the same way as post_init_per_suite, but for function init_per_testcase instead.

If Module:post_init_per_testcase/5 is not exported, common_test will attempt to call Module:post_init_per_testcase(TestcaseName, Config, Return, CTHState) instead. This is for backwards compatibility.

pre_end_per_group(SuiteName, GroupName, EndData, CTHState)

(since OTP 19.3) (optional)

-callback pre_end_per_group(SuiteName, GroupName, EndData, CTHState) -> Result
                               when
                                   SuiteName :: atom(),
                                   GroupName :: atom(),
                                   EndData :: Config | SkipOrFail,
                                   Config :: [{Key, Value}],
                                   NewConfig :: [{Key, Value}],
                                   CTHState :: term(),
                                   NewCTHState :: term(),
                                   Result :: {NewConfig | SkipOrFail, NewCTHState},
                                   SkipOrFail :: {fail, Reason} | {skip, Reason},
                                   Key :: atom(),
                                   Value :: term(),
                                   Reason :: term().

This function is called before end_per_group if it exists. It behaves the same way as pre_init_per_suite, but for function end_per_group instead.

If Module:pre_end_per_group/4 is not exported, common_test will attempt to call Module:pre_end_per_group(GroupName, EndData, CTHState) instead. This is for backwards compatibility.

pre_end_per_suite(SuiteName, EndData, CTHState)

(since OTP R14B02) (optional)

-callback pre_end_per_suite(SuiteName, EndData, CTHState) -> Result
                               when
                                   SuiteName :: atom(),
                                   EndData :: Config | SkipOrFail,
                                   Config :: [{Key, Value}],
                                   NewConfig :: [{Key, Value}],
                                   CTHState :: term(),
                                   NewCTHState :: term(),
                                   Result :: {NewConfig | SkipOrFail, NewCTHState},
                                   SkipOrFail :: {fail, Reason} | {skip, Reason},
                                   Key :: atom(),
                                   Value :: term(),
                                   Reason :: term().

This function is called before end_per_suite if it exists. It behaves the same way as pre_init_per_suite, but for function end_per_suite instead.

pre_end_per_testcase(SuiteName, TestcaseName, EndData, CTHState)

(since OTP 19.3) (optional)

-callback pre_end_per_testcase(SuiteName, TestcaseName, EndData, CTHState) -> Result
                                  when
                                      SuiteName :: atom(),
                                      TestcaseName :: atom(),
                                      EndData :: Config,
                                      Config :: [{Key, Value}],
                                      NewConfig :: [{Key, Value}],
                                      CTHState :: term(),
                                      NewCTHState :: term(),
                                      Result :: {NewConfig, NewCTHState},
                                      Key :: atom(),
                                      Value :: term().

This function is called before end_per_testcase if it exists. It behaves the same way as pre_end_per_suite, but for function end_per_testcase instead.

This function cannot change the result of the test case by returning skip or fail tuples, but it may insert items in Config that can be read in end_per_testcase/2 or in post_end_per_testcase/5.

If Module:pre_end_per_testcase/4 is not exported, common_test will attempt to call Module:pre_end_per_testcase(TestcaseName, EndData, CTHState) instead. This is for backwards compatibility.

pre_init_per_group(SuiteName, GroupName, InitData, CTHState)

(since OTP 19.3) (optional)

-callback pre_init_per_group(SuiteName, GroupName, InitData, CTHState) -> Result
                                when
                                    SuiteName :: atom(),
                                    GroupName :: atom(),
                                    InitData :: Config | SkipOrFail,
                                    Config :: [{Key, Value}],
                                    NewConfig :: [{Key, Value}],
                                    CTHState :: term(),
                                    NewCTHState :: term(),
                                    Result :: {NewConfig | SkipOrFail, NewCTHState},
                                    SkipOrFail :: {fail, Reason} | {skip, Reason},
                                    Key :: atom(),
                                    Value :: term(),
                                    Reason :: term().

This function is called before init_per_group if it exists. It behaves the same way as pre_init_per_suite, but for function init_per_group instead.

If Module:pre_init_per_group/4 is not exported, common_test will attempt to call Module:pre_init_per_group(GroupName, InitData, CTHState) instead. This is for backwards compatibility.

pre_init_per_suite(SuiteName, InitData, CTHState)

(since OTP R14B02) (optional)

-callback pre_init_per_suite(SuiteName, InitData, CTHState) -> Result
                                when
                                    SuiteName :: atom(),
                                    InitData :: Config | SkipOrFail,
                                    Config :: [{Key, Value}],
                                    NewConfig :: [{Key, Value}],
                                    CTHState :: term(),
                                    NewCTHState :: term(),
                                    Result :: {Return, NewCTHState},
                                    Return :: NewConfig | SkipOrFail,
                                    SkipOrFail :: {fail, Reason} | {skip, Reason},
                                    Key :: atom(),
                                    Value :: term(),
                                    Reason :: term().

This function is called before init_per_suite if it exists. It typically contains initialization/logging that must be done before init_per_suite is called. If {skip,Reason} or {fail,Reason} is returned, init_per_suite and all test cases of the suite are skipped and Reason printed in the overview log of the suite.

SuiteName is the name of the suite to be run.

InitData is the original configuration list of the test suite, or a SkipOrFail tuple if a previous CTH has returned this.

CTHState is the current internal state of the CTH.

Return is the result of the init_per_suite function. If it is {skip,Reason} or {fail,Reason}, init_per_suite is never called, instead the initiation is considered to be skipped or failed, respectively. If a NewConfig list is returned, init_per_suite is called with that NewConfig list. For more details, see section Pre Hooks in the User's Guide.

This function is called only if the CTH is added before init_per_suite is run. For details, see section CTH Scope in the User's Guide.

pre_init_per_testcase(SuiteName, TestcaseName, InitData, CTHState)

(since OTP 19.3) (optional)

-callback pre_init_per_testcase(SuiteName, TestcaseName, InitData, CTHState) -> Result
                                   when
                                       SuiteName :: atom(),
                                       TestcaseName :: atom(),
                                       InitData :: Config | SkipOrFail,
                                       Config :: [{Key, Value}],
                                       NewConfig :: [{Key, Value}],
                                       CTHState :: term(),
                                       NewCTHState :: term(),
                                       Result :: {NewConfig | SkipOrFail, NewCTHState},
                                       SkipOrFail :: {fail, Reason} | {skip, Reason},
                                       Key :: atom(),
                                       Value :: term(),
                                       Reason :: term().

This function is called before init_per_testcase if it exists. It behaves the same way as pre_init_per_suite, but for function init_per_testcase instead.

If Module:pre_init_per_testcase/4 is not exported, common_test will attempt to call Module:pre_init_per_testcase(TestcaseName, InitData, CTHState) instead. This is for backwards compatibility.

CTHs cannot be added here right now. That feature may be added in a later release, but it would right now break backwards compatibility.

terminate(Hooks)

(since OTP R14B02) (optional)

-callback terminate(CTHState) -> term() when CTHState :: term().

This function is called at the end of a CTH scope. The returned term is ignored.

ct_master

Distributed test execution control for Common Test.

This module exports functions for running Common Test nodes on multiple hosts in parallel.

Summary

Types

test_spec()

Filename of test spec to be executed.

Functions

abort()

Stops all running tests.

abort(Nodes)

Stops tests on specified nodes.

basic_html(Bool)

If set to true, the ct_master logs are written on a primitive HTML format, not using the Common Test CSS style sheet.

get_event_mgr_ref()

Gets a reference to the Common Test master event manager. The reference can be used to, for example, add a user-specific event handler while tests are running.

progress()

Returns test progress. If Status is ongoing, tests are running on the node and are not yet finished.

run(TestSpecs)

Run tests on spawned nodes as specified in TestSpecs (see run/4).

run(TestSpecs, InclNodes, ExclNodes)

Equivalent to run(TestSpecs, false, InclNodes, ExclNodes).

run(TestSpecs, AllowUserTerms, InclNodes, ExclNodes)

Tests are spawned on the nodes as specified in TestSpecs. Each specification in TestSpec is handled separately. However, it is also possible to specify a list of specifications to be merged into one specification before the tests are executed. Any test without a particular node specification is also executed on the nodes in InclNodes. Nodes in the ExclNodes list are excluded from the test.

run_on_node(TestSpecs, Node)

Equivalent to run_on_node(TestSpecs, false, Node).

run_on_node(TestSpecs, AllowUserTerms, Node)

Tests are spawned on Node according to TestSpecs.

run_test(Node, Opts)

Tests are spawned on Node using ct:run_test/1

Types

test_spec()

-type test_spec() :: file:name_all().

Filename of test spec to be executed.

Functions

abort()

-spec abort() -> ok.

Stops all running tests.

abort(Nodes)

-spec abort(Nodes) -> ok when Nodes :: Node | [Node], Node :: node().

Stops tests on specified nodes.

basic_html(Bool)

(since OTP R15B01)

-spec basic_html(Bool) -> ok when Bool :: boolean().

If set to true, the ct_master logs are written on a primitive HTML format, not using the Common Test CSS style sheet.

get_event_mgr_ref()

(since OTP 17.5)

-spec get_event_mgr_ref() -> atom().

Gets a reference to the Common Test master event manager. The reference can be used to, for example, add a user-specific event handler while tests are running.

Example:

gen_event:add_handler(ct_master:get_event_mgr_ref(), my_ev_h, [])

progress()

-spec progress() -> [{Node, Status}] when Node :: node(), Status :: atom().

Returns test progress. If Status is ongoing, tests are running on the node and are not yet finished.

run(TestSpecs)

-spec run(TestSpecs) -> [{Specs, ok} | {error, Reason}]
             when
                 TestSpecs :: TestSpec | [TestSpec] | [[TestSpec]],
                 TestSpec :: test_spec(),
                 Specs :: [file:filename_all()],
                 Reason :: term().

Run tests on spawned nodes as specified in TestSpecs (see run/4).

Equivalent to run(TestSpecs, false, [], []) if called with TestSpecs being list of strings;

Equivalent to run([TS], false, [], []) if called with TS being string.

run(TestSpecs, InclNodes, ExclNodes)

-spec run(TestSpecs, InclNodes, ExclNodes) -> [{Specs, ok} | {error, Reason}]
             when
                 TestSpecs :: TestSpec | [TestSpec] | [[TestSpec]],
                 TestSpec :: test_spec(),
                 InclNodes :: [node()],
                 ExclNodes :: [node()],
                 Specs :: [file:filename_all()],
                 Reason :: term().

Equivalent to run(TestSpecs, false, InclNodes, ExclNodes).

run(TestSpecs, AllowUserTerms, InclNodes, ExclNodes)

-spec run(TestSpecs, AllowUserTerms, InclNodes, ExclNodes) -> [{Specs, ok} | {error, Reason}]
             when
                 TestSpecs :: TestSpec | [TestSpec] | [[TestSpec]],
                 TestSpec :: test_spec(),
                 AllowUserTerms :: boolean(),
                 InclNodes :: [node()],
                 ExclNodes :: [node()],
                 Specs :: [file:filename_all()],
                 Reason :: term().

Tests are spawned on the nodes as specified in TestSpecs. Each specification in TestSpec is handled separately. However, it is also possible to specify a list of specifications to be merged into one specification before the tests are executed. Any test without a particular node specification is also executed on the nodes in InclNodes. Nodes in the ExclNodes list are excluded from the test.

run_on_node(TestSpecs, Node)

-spec run_on_node(TestSpecs, Node) -> [{Specs, ok} | {error, Reason}]
                     when
                         TestSpecs :: TestSpec | [TestSpec] | [[TestSpec]],
                         TestSpec :: test_spec(),
                         Node :: node(),
                         Specs :: [file:filename_all()],
                         Reason :: term().

Equivalent to run_on_node(TestSpecs, false, Node).

run_on_node(TestSpecs, AllowUserTerms, Node)

-spec run_on_node(TestSpecs, AllowUserTerms, Node) -> [{Specs, ok} | {error, Reason}]
                     when
                         TestSpecs :: TestSpec | [TestSpec] | [[TestSpec]],
                         TestSpec :: test_spec(),
                         AllowUserTerms :: boolean(),
                         Node :: node(),
                         Specs :: [file:filename_all()],
                         Reason :: term().

Tests are spawned on Node according to TestSpecs.

run_test(Node, Opts)

-spec run_test(Node, Opts) -> ok
                  when
                      Node :: node(),
                      Opts :: [OptTuples],
                      OptTuples ::
                          {dir, TestDirs} |
                          {suite, Suites} |
                          {group, Groups} |
                          {testcase, Cases} |
                          {spec, TestSpecs} |
                          {join_specs, boolean()} |
                          {label, Label} |
                          {config, CfgFiles} |
                          {userconfig, UserConfig} |
                          {allow_user_terms, boolean()} |
                          {logdir, LogDir} |
                          {silent_connections, Conns} |
                          {stylesheet, CSSFile} |
                          {cover, CoverSpecFile} |
                          {cover_stop, boolean()} |
                          {step, StepOpts} |
                          {event_handler, EventHandlers} |
                          {include, InclDirs} |
                          {auto_compile, boolean()} |
                          {abort_if_missing_suites, boolean()} |
                          {create_priv_dir, CreatePrivDir} |
                          {multiply_timetraps, M} |
                          {scale_timetraps, boolean()} |
                          {repeat, N} |
                          {duration, DurTime} |
                          {until, StopTime} |
                          {force_stop, ForceStop} |
                          {decrypt, DecryptKeyOrFile} |
                          {refresh_logs, LogDir} |
                          {logopts, LogOpts} |
                          {verbosity, VLevels} |
                          {basic_html, boolean()} |
                          {esc_chars, boolean()} |
                          {keep_logs, KeepSpec} |
                          {ct_hooks, CTHs} |
                          {ct_hooks_order, CTHsOrder} |
                          {enable_builtin_hooks, boolean()} |
                          {release_shell, boolean()},
                      TestDirs :: [string()] | string(),
                      Suites :: [string()] | [atom()] | string() | atom(),
                      Cases :: [atom()] | atom(),
                      Groups :: GroupNameOrPath | [GroupNameOrPath],
                      GroupNameOrPath :: [atom()] | atom() | all,
                      TestSpecs :: [string()] | string(),
                      Label :: string() | atom(),
                      CfgFiles :: [string()] | string(),
                      UserConfig :: [{CallbackMod, CfgStrings}] | {CallbackMod, CfgStrings},
                      CallbackMod :: atom(),
                      CfgStrings :: [string()] | string(),
                      LogDir :: string(),
                      Conns :: all | [atom()],
                      CSSFile :: string(),
                      CoverSpecFile :: string(),
                      StepOpts :: [StepOpt],
                      StepOpt :: config | keep_inactive,
                      EventHandlers :: EH | [EH],
                      EH :: atom() | {atom(), InitArgs} | {[atom()], InitArgs},
                      InitArgs :: [term()],
                      InclDirs :: [string()] | string(),
                      CreatePrivDir :: auto_per_run | auto_per_tc | manual_per_tc,
                      M :: integer(),
                      N :: integer(),
                      DurTime :: HHMMSS,
                      HHMMSS :: string(),
                      StopTime :: YYMoMoDDHHMMSS | HHMMSS,
                      YYMoMoDDHHMMSS :: string(),
                      ForceStop :: skip_rest | boolean(),
                      DecryptKeyOrFile :: {key, DecryptKey} | {file, DecryptFile},
                      DecryptKey :: string(),
                      DecryptFile :: string(),
                      LogOpts :: [LogOpt],
                      LogOpt :: no_nl | no_src,
                      VLevels :: VLevel | [{Category, VLevel}],
                      VLevel :: integer(),
                      Category :: atom(),
                      KeepSpec :: all | pos_integer(),
                      CTHs :: [CTHModule | {CTHModule, CTHInitArgs}],
                      CTHsOrder :: atom(),
                      CTHModule :: atom(),
                      CTHInitArgs :: term().

Tests are spawned on Node using ct:run_test/1

ct_netconfc

NETCONF client module.

NETCONF client module compliant with RFC 6241, NETCONF Configuration Protocol, and RFC 6242, Using the NETCONF Configuration Protocol over Secure SHell (SSH), and with support for RFC 5277, NETCONF Event Notifications.

Connecting to a NETCONF server

Call connect/1,2 to establish a connection to a server, then pass the returned handle to session/1-3 to establish a NETCONF session on a new SSH channel. Each call to session/1-3 establishes a new session on the same connection, and results in a hello message to the server.

Alternately, open/1,2 can be used to establish a single session on a dedicated connection. (Or, equivalently, only_open/1,2 followed by hello/1-3.)

Connect/session options can be specified in a configuration file with entries like the following.

{server_id(), [option()]}.

The server_id/0 or an associated ct:target_name/0 can then be passed to the aforementioned functions to use the referenced configuration.

Signaling

Protocol operations in the NETCONF protocol are realized as remote procedure calls (RPCs) from client to server and a corresponding reply from server to client. RPCs are sent using like-named functions (eg. edit_config/3-5 to send an edit-config RPC), with the server reply as return value. There are functions for each RPC defined in RFC 6241 and the create-subscription RPC from RFC 5277, all of which are wrappers on send_rpc/2,3, that can be used to send an arbitrary RPC not defined in RFC 6241 or RFC 5277.

All of the signaling functions have one variant with a Timeout argument and one without, corresponding to an infinite timeout. The latter is inappropriate in most cases since a non-response by the server or a missing message-id causes the call to hang indefinitely.

Logging

The NETCONF server uses error_logger for logging of NETCONF traffic. A special purpose error handler is implemented in ct_conn_log_h. To use this error handler, add the cth_conn_log hook in the test suite, for example:

suite() ->
    [{ct_hooks, [{cth_conn_log, [{ct:conn_log_mod(), ct:conn_log_options()}]}]}].

conn_log_mod() is the name of the Common Test module implementing the connection protocol, for example, ct_netconfc.

Hook option log_type specifies the type of logging:

raw - The sent and received NETCONF data is logged to a separate text file "as is" without any formatting. A link to the file is added to the test case HTML log.

pretty - The sent and received NETCONF data is logged to a separate text file with XML data nicely indented. A link to the file is added to the test case HTML log.

html (default) - The sent and received NETCONF traffic is pretty printed directly in the test case HTML log.

silent - NETCONF traffic is not logged.

By default, all NETCONF traffic is logged in one single log file. However, different connections can be logged in separate files. To do this, use hook option hosts and list the names of the servers/connections to be used in the suite. The connections must be named for this to work, that is, they must be opened with open/2.

Option hosts has no effect if log_type is set to html or silent.

The hook options can also be specified in a configuration file with configuration variable ct_conn_log:

{ct_conn_log,[{ct:conn_log_mod(), ct:conn_log_options()}]}.

For example:

{ct_conn_log,[{ct_netconfc,[{log_type,pretty},
                            {hosts,[ct:key_or_name()]}]}]}

Note

Hook options specified in a configuration file overwrite the hard-coded hook options in the test suite.

Logging Example 1:

The following ct_hooks statement causes pretty printing of NETCONF traffic to separate logs for the connections named nc_server1 and nc_server2. Any other connections are logged to default NETCONF log.

suite() ->
   [{ct_hooks, [{cth_conn_log, [{ct_netconfc,[{log_type,pretty}},
                                              {hosts,[nc_server1,nc_server2]}]}
                               ]}]}].

Connections must be opened as follows:

open(nc_server1,[...]),
open(nc_server2,[...]).

Logging Example 2:

The following configuration file causes raw logging of all NETCONF traffic in to one single text file:

{ct_conn_log,[{ct_netconfc,[{log_type,raw}]}]}.

The ct_hooks statement must look as follows:

suite() ->
    [{ct_hooks, [{cth_conn_log, []}]}].

The same ct_hooks statement without the configuration file would cause HTML logging of all NETCONF connections in to the test case HTML log.

Summary

Types

client()

Handle to a NETCONF session, as required by signaling functions.

error_reason()

handle()

Handle to a connection to a NETCONF server as returned by connect/1,2, or to a session as returned by session/1-3, open/1,2, or only_open/1,2.

host()

netconf_db()

notification()

Event notification messages sent as a result of calls to create_subscription/2,3.

option()

Options host and port specify the server endpoint to which to connect, and are passed directly to ssh:connect/4, as are arbitrary ssh options. Common options are user, password and user_dir.

server_id()

Identity of connection or session configuration in a configuration file.

session_option()

simple_xml()

Representation of XML, as described in application xmerl.

stream_data()

stream_name()

streams()

Stream information as returned by get_event_streams/1-3. See RFC 5277, "XML Schema for Event Notifications", for detail on the format of the string values.

xml_attribute_tag()

xml_attribute_value()

xml_attributes()

xml_content()

xml_tag()

xpath()

xs_datetime()

Date and time of a startTime/stopTime element in an RFC 5277 create-subscription request. Of XML primitive type dateTime, which has the (informal) form

Functions

action(Client, Action)

Equivalent to action/3.

action(Client, Action, Timeout)

Executes an action. If the return type is void, ok is returned instead of {ok,[simple_xml()]}.

close_session(Client)

Equivalent to close_session/2.

close_session(Client, Timeout)

Requests graceful termination of the session associated with the client.

connect(Options)

Opens an SSH connection to a NETCONF server.

connect(KeyOrName, ExtraOptions)

Open an SSH connection to a named NETCONF server.

copy_config(Client, Target, Source)

Equivalent to copy_config/4.

copy_config(Client, Target, Source, Timeout)

Copies configuration data.

create_subscription/2

Equivalent to create_subscription/3.

create_subscription/3

Creates a subscription for event notifications by sending an RFC 5277 create-subscription RPC to the server. The calling process receives events as messages of type notification/0.

delete_config(Client, Target)

Equivalent to delete_config/3.

delete_config(Client, Target, Timeout)

Deletes configuration data.

disconnect(Conn)

Closes the given SSH connection.

edit_config(Client, Target, Config)

Equivalent to edit_config/5.

edit_config/4

Equivalent to edit_config/5.

edit_config(Client, Target, Config, OptParams, Timeout)

Edits configuration data.

get(Client, Filter)

Equivalent to get/3.

get(Client, Filter, Timeout)

Gets data.

get_capabilities(Client)

Equivalent to get_capabilities/2.

get_capabilities(Client, Timeout)

Returns the server capabilities as received in its hello message.

get_config(Client, Source, Filter)

Equivalent to get_config/4.

get_config(Client, Source, Filter, Timeout)

Gets configuration data.

get_event_streams(Client)

Equivalent to get_event_streams/3.

get_event_streams/2

Equivalent to get_event_streams/3.

get_event_streams(Client, Streams, Timeout)

Sends a request to get the specified event streams.

get_session_id(Client)

Equivalent to get_session_id/2.

get_session_id(Client, Timeout)

Returns the session Id associated with the specified client.

hello(Client)

Equivalent to hello/3.

hello(Client, Timeout)

Equivalent to hello/3.

hello(Client, Options, Timeout)

Exchanges hello messages with the server. Returns when the server hello has been received or after the specified timeout.

kill_session(Client, SessionId)

Equivalent to kill_session/3.

kill_session(Client, SessionId, Timeout)

Forces termination of the session associated with the supplied session Id.

lock(Client, Target)

Equivalent to lock/3.

lock(Client, Target, Timeout)

Locks the configuration target.

only_open(Options)

Opens a NETCONF session, but does not send hello.

only_open(KeyOrName, ExtraOptions)

Opens a named NETCONF session, but does not send hello.

open(Options)

Opens a NETCONF session and exchanges hello messages.

open(KeyOrName, ExtraOption)

Opens a named NETCONF session and exchanges hello messages.

send(Client, SimpleXml)

Equivalent to send/3.

send(Client, SimpleXml, Timeout)

Sends an XML document to the server.

send_rpc(Client, SimpleXml)

Equivalent to send_rpc/3.

send_rpc(Client, SimpleXml, Timeout)

Sends a NETCONF rpc request to the server.

session(Conn)

Equivalent to session/3.

session/2

Equivalent to session/3.

session(KeyOrName, Conn, Options)

Opens a NETCONF session as a channel on the given SSH connection, and exchanges hello messages with the server.

unlock(Client, Target)

Equivalent to unlock/3.

unlock(Client, Target, Timeout)

Unlocks the configuration target.

Types

client()

(since OTP R15B02)

-type client() :: handle() | server_id() | ct:target_name().

Handle to a NETCONF session, as required by signaling functions.

error_reason()

(not exported) (since OTP R15B02)

-type error_reason() :: term().

handle()

(since OTP R15B02)

-opaque handle()

Handle to a connection to a NETCONF server as returned by connect/1,2, or to a session as returned by session/1-3, open/1,2, or only_open/1,2.

host()

(not exported) (since OTP R15B02)

-type host() :: inet:hostname() | inet:ip_address().

netconf_db()

(not exported) (since OTP R15B02)

-type netconf_db() :: running | startup | candidate.

notification()

(since OTP R15B02)

-type notification() :: {notification, xml_attributes(), [simple_xml()]}.

Event notification messages sent as a result of calls to create_subscription/2,3.

option()

(not exported) (since OTP R15B02)

-type option() ::
          {host | ssh, host()} |
          {port, inet:port_number()} |
          {timeout, timeout()} |
          {capability, string() | [string()]} |
          {receiver, term()} |
          ssh:client_option().

Options host and port specify the server endpoint to which to connect, and are passed directly to ssh:connect/4, as are arbitrary ssh options. Common options are user, password and user_dir.

Option timeout specifies the number of milliseconds to allow for connection establishment and, if the function in question results in an outgoing hello message, reception of the server hello. The timeout applies to connection and hello independently; one timeout for connection establishment, another for hello reception.

Option receiver specifies a destination for incoming notification messages; a left operand of the send operator (!). If not specified then a process calling create_subscription/2,3 becomes the receiver, but explicitly setting a receiver makes it possible to receive notifications that are not ordered by calling this function. Multiple receiver options can be specified.

Receiver options are ignored by connect/1-3.

Option capability specifies the content of a corresponding element in an outgoing hello message, each option specifying the content of a single element. If no base NETCONF capability is configured then the RFC 4741 1.0 capability, "urn:ietf:params:netconf:base:1.0", is added, otherwise not. In particular, the RFC 6241 1.1 capability must be explicitly configured. NETCONF capabilities can be specified using the shorthand notation defined in RFC 6241, any capability string starting with a colon being prefixed by either "urn:ietf:params:netconf" or "urn:ietf:params:netconf:capability", as appropriate.

Capability options are ignored by connect/1-3 and only_open/1-2, which don't result in an outgoing hello message.

server_id()

(not exported) (since OTP R15B02)

-type server_id() :: atom().

Identity of connection or session configuration in a configuration file.

session_option()

(not exported) (since OTP R15B02)

-type session_option() ::
          {timeout, timeout()} | {receiver, term()} | {capability, string() | [string()]}.

simple_xml()

(not exported) (since OTP R15B02)

-type simple_xml() ::
          {xml_tag(), xml_attributes(), xml_content()} | {xml_tag(), xml_content()} | xml_tag().

Representation of XML, as described in application xmerl.

stream_data()

(not exported) (since OTP R15B02)

-type stream_data() ::
          {description, string()} |
          {replaySupport, string()} |
          {replayLogCreationTime, string()} |
          {replayLogAgedTime, string()}.

stream_name()

(not exported) (since OTP R15B02)

-type stream_name() :: string().

streams()

(not exported) (since OTP R15B02)

-type streams() :: [{stream_name(), [stream_data()]}].

Stream information as returned by get_event_streams/1-3. See RFC 5277, "XML Schema for Event Notifications", for detail on the format of the string values.

xml_attribute_tag()

(not exported) (since OTP R15B02)

-type xml_attribute_tag() :: atom().

xml_attribute_value()

(not exported) (since OTP R15B02)

-type xml_attribute_value() :: string().

xml_attributes()

(not exported) (since OTP R15B02)

-type xml_attributes() :: [{xml_attribute_tag(), xml_attribute_value()}].

xml_content()

(not exported) (since OTP R15B02)

-type xml_content() :: [simple_xml() | iolist()].

xml_tag()

(not exported) (since OTP R15B02)

-type xml_tag() :: atom().

xpath()

(not exported) (since OTP R15B02)

-type xpath() :: {xpath, string()}.

xs_datetime()

(not exported) (since OTP R15B02)

-type xs_datetime() :: string().

Date and time of a startTime/stopTime element in an RFC 5277 create-subscription request. Of XML primitive type dateTime, which has the (informal) form

[-]YYYY-MM-DDThh:mm:ss[.s][Z|(+|-)hh:mm]

where T and Z are literal and .s is one or more fractional seconds.

Functions

action(Client, Action)

(since OTP R15B02)

-spec action(Client, Action) -> Result
                when
                    Client :: client(),
                    Action :: simple_xml(),
                    Result :: ok | {ok, [simple_xml()]} | {error, error_reason()}.

Equivalent to action/3.

action(Client, Action, Timeout)

(since OTP R15B02)

-spec action(Client, Action, Timeout) -> Result
                when
                    Client :: client(),
                    Action :: simple_xml(),
                    Timeout :: timeout(),
                    Result :: ok | {ok, [simple_xml()]} | {error, error_reason()}.

Executes an action. If the return type is void, ok is returned instead of {ok,[simple_xml()]}.

close_session(Client)

(since OTP R15B02)

-spec close_session(Client) -> Result when Client :: client(), Result :: ok | {error, error_reason()}.

Equivalent to close_session/2.

close_session(Client, Timeout)

(since OTP R15B02)

-spec close_session(Client, Timeout) -> Result
                       when
                           Client :: client(),
                           Timeout :: timeout(),
                           Result :: ok | {error, error_reason()}.

Requests graceful termination of the session associated with the client.

When a NETCONF server receives a close-session request, it gracefully closes the session. The server releases any locks and resources associated with the session and gracefully closes any associated connections. Any NETCONF requests received after a close-session request are ignored.

connect(Options)

(since OTP 20.0)

-spec connect(Options) -> Result
                 when Options :: [option()], Result :: {ok, handle()} | {error, error_reason()}.

Opens an SSH connection to a NETCONF server.

If the server options are specified in a configuration file, use connect/2 instead.

The opaque handle/0 reference returned from this function is required as connection identifier when opening sessions over this connection, see session/1-3.

connect(KeyOrName, ExtraOptions)

(since OTP 20.0)

-spec connect(KeyOrName, ExtraOptions) -> Result
                 when
                     KeyOrName :: ct:key_or_name(),
                     ExtraOptions :: [option()],
                     Result :: {ok, handle()} | {error, error_reason()}.

Open an SSH connection to a named NETCONF server.

If KeyOrName is a configured server_id/0 or a target_name() associated with such an Id, then the options for this server are fetched from the configuration file.

The options list is added to those of the configuration file. If an option is specified in both lists, the configuration file takes precedence.

If the server is not specified in a configuration file, use connect/1 instead.

The opaque handle/0 reference returned from this function can be used as connection identifier when opening sessions over this connection, see session/1-3. However, if KeyOrName is a target_name(), that is, if the server is named through a call to ct:require/2 or a require statement in the test suite, then this name can be used instead of handle/0.

copy_config(Client, Target, Source)

(since OTP R15B02)

-spec copy_config(Client, Target, Source) -> Result
                     when
                         Client :: client(),
                         Target :: netconf_db(),
                         Source :: netconf_db(),
                         Result :: ok | {error, error_reason()}.

Equivalent to copy_config/4.

copy_config(Client, Target, Source, Timeout)

(since OTP R15B02)

-spec copy_config(Client, Target, Source, Timeout) -> Result
                     when
                         Client :: client(),
                         Target :: netconf_db(),
                         Source :: netconf_db(),
                         Timeout :: timeout(),
                         Result :: ok | {error, error_reason()}.

Copies configuration data.

Which source and target options that can be issued depends on the capabilities supported by the server. That is, :candidate and/or :startup are required.

create_subscription/2

(since OTP 22.1)

-spec create_subscription(Client, Values) -> Result
                             when
                                 Client :: client(),
                                 Values ::
                                     #{stream => Stream,
                                       filter => Filter,
                                       start => StartTime,
                                       stop => StopTime},
                                 Stream :: stream_name(),
                                 Filter :: simple_xml() | [simple_xml()],
                                 StartTime :: xs_datetime(),
                                 StopTime :: xs_datetime(),
                                 Result :: ok | {error, error_reason()};
                         (Client, list() | timeout()) -> Result
                             when Client :: client(), Result :: ok | {error, error_reason()}.

Equivalent to create_subscription/3.

create_subscription/3

(since OTP 22.1)

-spec create_subscription(Client, Values, Timeout) -> Result
                             when
                                 Client :: client(),
                                 Values ::
                                     #{stream => Stream,
                                       filter => Filter,
                                       start => StartTime,
                                       stop => StopTime},
                                 Stream :: stream_name(),
                                 Filter :: simple_xml() | [simple_xml()],
                                 StartTime :: xs_datetime(),
                                 StopTime :: xs_datetime(),
                                 Timeout :: timeout(),
                                 Result :: ok | {error, error_reason()};
                         (Client, list(), list() | timeout()) -> Result
                             when Client :: client(), Result :: ok | {error, error_reason()}.

Creates a subscription for event notifications by sending an RFC 5277 create-subscription RPC to the server. The calling process receives events as messages of type notification/0.

From RFC 5722, 2.1 Subscribing to Receive Event Notifications:

Stream - Indicates which stream of event is of interest. If not present, events in the default NETCONF stream are sent.

Filter - Indicates which subset of all possible events is of interest. The parameter format is the same as that of the filter parameter in the NETCONF protocol operations. If not present, all events not precluded by other parameters are sent.

StartTime - Used to trigger the replay feature and indicate that the replay is to start at the time specified. If StartTime is not present, this is not a replay subscription. It is not valid to specify start times that are later than the current time. If StartTime is specified earlier than the log can support, the replay begins with the earliest available notification. This parameter is of type dateTime and compliant to RFC 3339. Implementations must support time zones.

StopTime - Used with the optional replay feature to indicate the newest notifications of interest. If StopTime is not present, the notifications continues until the subscription is terminated. Must be used with and be later than StartTime. Values of StopTime in the future are valid. This parameter is of type dateTime and compliant to RFC 3339. Implementations must support time zones.

See RFC 5277 for more details. The requirement that StopTime must only be used with StartTime is not enforced, to allow an invalid request to be sent to the server.

Prior to OTP 22.1, this function was documented as having 15 variants in 6 arities. These are still exported for backwards compatibility, but no longer documented. The map-based variants documented above provide the same functionality with simpler arguments.

Note

create-subscription is no longer the only RPC with which NETCONF notifications can be ordered: RFC 8639 adds establish-subscription and future RFCs may add other methods. Specify a receiver option at session creation to provide a destination for incoming notifications independently of a call to create_subscription/2,3, and use send_rpc/2,3 to send establish-subscription and other arbitrary RPCs.

delete_config(Client, Target)

(since OTP R15B02)

-spec delete_config(Client, Target) -> Result
                       when
                           Client :: client(),
                           Target :: startup | candidate,
                           Result :: ok | {error, error_reason()}.

Equivalent to delete_config/3.

delete_config(Client, Target, Timeout)

(since OTP R15B02)

-spec delete_config(Client, Target, Timeout) -> Result
                       when
                           Client :: client(),
                           Target :: startup | candidate,
                           Timeout :: timeout(),
                           Result :: ok | {error, error_reason()}.

Deletes configuration data.

The running configuration cannot be deleted and :candidate or :startup must be advertised by the server.

disconnect(Conn)

(since OTP 20.0)

-spec disconnect(Conn) -> ok | {error, error_reason()} when Conn :: handle().

Closes the given SSH connection.

If there are open NETCONF sessions on the connection, these will be brutally aborted. To avoid this, close each session with close_session/1,2

edit_config(Client, Target, Config)

(since OTP R15B02)

-spec edit_config(Client, Target, Config) -> Result
                     when
                         Client :: client(),
                         Target :: netconf_db(),
                         Config :: simple_xml() | [simple_xml()],
                         Result :: ok | {error, error_reason()}.

Equivalent to edit_config/5.

edit_config/4

(since OTP R15B02)

-spec edit_config(Client, Target, Config, OptParams) -> Result
                     when
                         Client :: client(),
                         Target :: netconf_db(),
                         Config :: simple_xml() | [simple_xml()],
                         OptParams :: [simple_xml()],
                         Result :: ok | {error, error_reason()};
                 (Client, Target, Config, Timeout) -> Result
                     when
                         Client :: client(),
                         Target :: netconf_db(),
                         Config :: simple_xml(),
                         Timeout :: timeout(),
                         Result :: ok | {error, error_reason()}.

Equivalent to edit_config/5.

edit_config(Client, Target, Config, OptParams, Timeout)

(since OTP 18.0)

-spec edit_config(Client, Target, Config, OptParams, Timeout) -> Result
                     when
                         Client :: client(),
                         Target :: netconf_db(),
                         Config :: simple_xml() | [simple_xml()],
                         OptParams :: [simple_xml()],
                         Timeout :: timeout(),
                         Result :: ok | {error, error_reason()}.

Edits configuration data.

By default only the running target is available, unless the server includes :candidate or :startup in its list of capabilities.

OptParams can be used for specifying optional parameters (default-operation, test-option, or error-option) to be added to the edit-config request. The value must be a list containing valid simple XML, for example:

[{'default-operation', ["none"]},
 {'error-option', ["rollback-on-error"]}]

If OptParams is not given, the default value [] is used.

get(Client, Filter)

(since OTP R15B02)

-spec get(Client, Filter) -> Result
             when
                 Client :: client(),
                 Filter :: simple_xml() | xpath(),
                 Result :: {ok, [simple_xml()]} | {error, error_reason()}.

Equivalent to get/3.

get(Client, Filter, Timeout)

(since OTP R15B02)

-spec get(Client, Filter, Timeout) -> Result
             when
                 Client :: client(),
                 Filter :: simple_xml() | xpath(),
                 Timeout :: timeout(),
                 Result :: {ok, [simple_xml()]} | {error, error_reason()}.

Gets data.

This operation returns both configuration and state data from the server.

Filter type xpath can be used only if the server supports :xpath.

get_capabilities(Client)

(since OTP R15B02)

-spec get_capabilities(Client) -> Result
                          when Client :: client(), Result :: [string()] | {error, error_reason()}.

Equivalent to get_capabilities/2.

get_capabilities(Client, Timeout)

(since OTP R15B02)

-spec get_capabilities(Client, Timeout) -> Result
                          when
                              Client :: client(),
                              Timeout :: timeout(),
                              Result :: [string()] | {error, error_reason()}.

Returns the server capabilities as received in its hello message.

get_config(Client, Source, Filter)

(since OTP R15B02)

-spec get_config(Client, Source, Filter) -> Result
                    when
                        Client :: client(),
                        Source :: netconf_db(),
                        Filter :: simple_xml() | xpath(),
                        Result :: {ok, [simple_xml()]} | {error, error_reason()}.

Equivalent to get_config/4.

get_config(Client, Source, Filter, Timeout)

(since OTP R15B02)

-spec get_config(Client, Source, Filter, Timeout) -> Result
                    when
                        Client :: client(),
                        Source :: netconf_db(),
                        Filter :: simple_xml() | xpath(),
                        Timeout :: timeout(),
                        Result :: {ok, [simple_xml()]} | {error, error_reason()}.

Gets configuration data.

To be able to access another source than running, the server must advertise :candidate and/or :startup.

Filter type xpath can be used only if the server supports :xpath.

get_event_streams(Client)

(since OTP 20.0)

-spec get_event_streams(Client) -> Result
                           when Client :: client(), Result :: {ok, streams()} | {error, error_reason()}.

Equivalent to get_event_streams/3.

get_event_streams/2

(since OTP R15B02)

-spec get_event_streams(Client, Timeout) -> Result
                           when
                               Client :: client(),
                               Timeout :: timeout(),
                               Result :: {ok, streams()} | {error, error_reason()};
                       (Client, Streams) -> Result
                           when
                               Client :: client(),
                               Streams :: [stream_name()],
                               Result :: {ok, streams()} | {error, error_reason()}.

Equivalent to get_event_streams/3.

get_event_streams(Client, Streams, Timeout)

(since OTP R15B02)

-spec get_event_streams(Client, Streams, Timeout) -> Result
                           when
                               Client :: client(),
                               Streams :: [stream_name()],
                               Timeout :: timeout(),
                               Result :: {ok, streams()} | {error, error_reason()}.

Sends a request to get the specified event streams.

Streams is a list of stream names. The following filter is sent to the NETCONF server in a get request:

<netconf xmlns="urn:ietf:params:xml:ns:netmod:notification">
  <streams>
    <stream>
      <name>StreamName1</name>
    </stream>
    <stream>
      <name>StreamName2</name>
    </stream>
    ...
  </streams>
</netconf>

If Streams is an empty list, all streams are requested by sending the following filter:

<netconf xmlns="urn:ietf:params:xml:ns:netmod:notification">
  <streams/>
</netconf>

If more complex filtering is needed, use ct_netconfc:get/2,3 and specify the exact filter according to "XML Schema for Event Notifications" in RFC 5277.

get_session_id(Client)

(since OTP R15B02)

-spec get_session_id(Client) -> Result
                        when Client :: client(), Result :: pos_integer() | {error, error_reason()}.

Equivalent to get_session_id/2.

get_session_id(Client, Timeout)

(since OTP R15B02)

-spec get_session_id(Client, Timeout) -> Result
                        when
                            Client :: client(),
                            Timeout :: timeout(),
                            Result :: pos_integer() | {error, error_reason()}.

Returns the session Id associated with the specified client.

hello(Client)

(since OTP R15B02)

-spec hello(Client) -> Result when Client :: handle(), Result :: ok | {error, error_reason()}.

Equivalent to hello/3.

hello(Client, Timeout)

(since OTP R15B02)

-spec hello(Client, Timeout) -> Result
               when Client :: handle(), Timeout :: timeout(), Result :: ok | {error, error_reason()}.

Equivalent to hello/3.

hello(Client, Options, Timeout)

(since OTP 17.5.3)

-spec hello(Client, Options, Timeout) -> Result
               when
                   Client :: handle(),
                   Options :: [{capability, [string()]}],
                   Timeout :: timeout(),
                   Result :: ok | {error, error_reason()}.

Exchanges hello messages with the server. Returns when the server hello has been received or after the specified timeout.

Note that capabilities for an outgoing hello can be passed directly to open/2.

kill_session(Client, SessionId)

(since OTP R15B02)

-spec kill_session(Client, SessionId) -> Result
                      when
                          Client :: client(),
                          SessionId :: pos_integer(),
                          Result :: ok | {error, error_reason()}.

Equivalent to kill_session/3.

kill_session(Client, SessionId, Timeout)

(since OTP R15B02)

-spec kill_session(Client, SessionId, Timeout) -> Result
                      when
                          Client :: client(),
                          SessionId :: pos_integer(),
                          Timeout :: timeout(),
                          Result :: ok | {error, error_reason()}.

Forces termination of the session associated with the supplied session Id.

The server side must abort any ongoing operations, release any locks and resources associated with the session, and close any associated connections.

Only if the server is in the confirmed commit phase, the configuration is restored to its state before entering the confirmed commit phase. Otherwise, no configuration rollback is performed.

If the specified SessionId is equal to the current session Id, an error is returned.

lock(Client, Target)

(since OTP R15B02)

-spec lock(Client, Target) -> Result
              when Client :: client(), Target :: netconf_db(), Result :: ok | {error, error_reason()}.

Equivalent to lock/3.

lock(Client, Target, Timeout)

(since OTP R15B02)

-spec lock(Client, Target, Timeout) -> Result
              when
                  Client :: client(),
                  Target :: netconf_db(),
                  Timeout :: timeout(),
                  Result :: ok | {error, error_reason()}.

Locks the configuration target.

Which target parameters that can be used depends on if :candidate and/or :startup are supported by the server. If successful, the configuration system of the device is unavailable to other clients (NETCONF, CORBA, SNMP, and so on). Locks are intended to be short-lived.

Operation kill_session/2,3 can be used to force the release of a lock owned by another NETCONF session. How this is achieved by the server side is implementation-specific.

only_open(Options)

(since OTP R15B02)

-spec only_open(Options) -> Result
                   when Options :: [option()], Result :: {ok, handle()} | {error, error_reason()}.

Opens a NETCONF session, but does not send hello.

As open/1, but does not send a hello message.

only_open(KeyOrName, ExtraOptions)

(since OTP R15B02)

-spec only_open(KeyOrName, ExtraOptions) -> Result
                   when
                       KeyOrName :: ct:key_or_name(),
                       ExtraOptions :: [option()],
                       Result :: {ok, handle()} | {error, error_reason()}.

Opens a named NETCONF session, but does not send hello.

As open/2, but does not send a hello message.

open(Options)

(since OTP R15B02)

-spec open(Options) -> Result
              when Options :: [option()], Result :: {ok, handle()} | {error, error_reason()}.

Opens a NETCONF session and exchanges hello messages.

If the server options are specified in a configuration file, or if a named client is needed for logging purposes (see section Logging in this module), use open/2 instead.

The opaque handle/0 reference returned from this function is required as client identifier when calling any other function in this module.

open(KeyOrName, ExtraOption)

(since OTP R15B02)

-spec open(KeyOrName, ExtraOption) -> Result
              when
                  KeyOrName :: ct:key_or_name(),
                  ExtraOption :: [option()],
                  Result :: {ok, handle()} | {error, error_reason()}.

Opens a named NETCONF session and exchanges hello messages.

If KeyOrName is a configured server_id/0 or a target_name() associated with such an Id, then the options for this server are fetched from the configuration file.

The options list is added to those of the configuration file. If an option is specified in both lists, the configuration file take precedence.

If the server is not specified in a configuration file, use open/1 instead.

The opaque handle/0 reference returned from this function can be used as client identifier when calling any other function in this module. However, if KeyOrName is a target_name(), that is, if the server is named through a call to ct:require/2 or a require statement in the test suite, then this name can be used instead of handle/0.

See also ct:require/2.

send(Client, SimpleXml)

(since OTP R16B02)

-spec send(Client, SimpleXml) -> Result
              when
                  Client :: client(),
                  SimpleXml :: simple_xml(),
                  Result :: simple_xml() | {error, error_reason()}.

Equivalent to send/3.

send(Client, SimpleXml, Timeout)

(since OTP R16B02)

-spec send(Client, SimpleXml, Timeout) -> Result
              when
                  Client :: client(),
                  SimpleXml :: simple_xml(),
                  Timeout :: timeout(),
                  Result :: simple_xml() | {error, error_reason()}.

Sends an XML document to the server.

The specified XML document is sent "as is" to the server. This function can be used for sending XML documents that cannot be expressed by other interface functions in this module.

send_rpc(Client, SimpleXml)

(since OTP R16B02)

-spec send_rpc(Client, SimpleXml) -> Result
                  when
                      Client :: client(),
                      SimpleXml :: simple_xml(),
                      Result :: [simple_xml()] | {error, error_reason()}.

Equivalent to send_rpc/3.

send_rpc(Client, SimpleXml, Timeout)

(since OTP R16B02)

-spec send_rpc(Client, SimpleXml, Timeout) -> Result
                  when
                      Client :: client(),
                      SimpleXml :: simple_xml(),
                      Timeout :: timeout(),
                      Result :: [simple_xml()] | {error, error_reason()}.

Sends a NETCONF rpc request to the server.

The specified XML document is wrapped in a valid NETCONF rpc request and sent to the server. The message-id and namespace attributes are added to element rpc.

This function can be used for sending rpc requests that cannot be expressed by other interface functions in this module.

session(Conn)

(since OTP 20.0)

-spec session(Conn) -> Result when Conn :: handle(), Result :: {ok, handle()} | {error, error_reason()}.

Equivalent to session/3.

session/2

(since OTP 20.0)

-spec session(Conn, Options) -> Result
                 when
                     Conn :: handle(),
                     Options :: [session_option()],
                     Result :: {ok, handle()} | {error, error_reason()};
             (KeyOrName, Conn) -> Result
                 when
                     KeyOrName :: ct:key_or_name(),
                     Conn :: handle(),
                     Result :: {ok, handle()} | {error, error_reason()}.

Equivalent to session/3.

session(KeyOrName, Conn, Options)

(since OTP 20.0)

-spec session(KeyOrName, Conn, Options) -> Result
                 when
                     Conn :: handle(),
                     Options :: [session_option()],
                     KeyOrName :: ct:key_or_name(),
                     Result :: {ok, handle()} | {error, error_reason()}.

Opens a NETCONF session as a channel on the given SSH connection, and exchanges hello messages with the server.

The opaque handle/0 reference returned from this function can be used as client identifier when calling any other function in this module. However, if KeyOrName is used and it is a target_name(), that is, if the server is named through a call to ct:require/2 or a require statement in the test suite, then this name can be used instead of handle/0.

unlock(Client, Target)

(since OTP R15B02)

-spec unlock(Client, Target) -> Result
                when Client :: client(), Target :: netconf_db(), Result :: ok | {error, error_reason()}.

Equivalent to unlock/3.

unlock(Client, Target, Timeout)

(since OTP R15B02)

-spec unlock(Client, Target, Timeout) -> Result
                when
                    Client :: client(),
                    Target :: netconf_db(),
                    Timeout :: timeout(),
                    Result :: ok | {error, error_reason()}.

Unlocks the configuration target.

If the client earlier has acquired a lock through lock/2,3, this operation releases the associated lock. To access another target than running, the server must support :candidate and/or :startup.

ct_property_test

Support in Common Test for running property-based tests.

This module helps running property-based tests in the Common Test framework. One (or more) of the property testing tools

QuickCheck,

PropEr or

Triq

is assumed to be installed.

The idea with this module is to have a Common Test test suite calling a property testing tool with special property test suites as defined by that tool. The tests are collected in the test directory of the application. The test directory has a subdirectory property_test, where everything needed for the property tests are collected. The usual Erlang application directory structure is assumed.

A typical Common Test test suite using ct_property_test is organized as follows:

-module(my_prop_test_SUITE).
-compile(export_all).

-include_lib("common_test/include/ct.hrl").

all() -> [prop_ftp_case].

init_per_suite(Config) ->
    ct_property_test:init_per_suite(Config).

%%%---- test case
prop_ftp_case(Config) ->
    ct_property_test:quickcheck(
      ftp_simple_client_server:prop_ftp(),
      Config
     ).

and the the property test module (in this example ftp_simple_client_server.erl) as almost a usual property testing module (More examples are in the User's Guide):

-module(ftp_simple_client_server).
-export([prop_ftp/0...]).

-include_lib("common_test/include/ct_property_test.hrl").

prop_ftp() ->
    ?FORALL( ....

Summary

Types

arguments()

command()

command_list()

dynamic_state()

function_name()

history()

init_command()

parallel_testcase()

set_command()

statem_result()

symbolic_call()

symbolic_state()

symbolic_var()

Functions

cmnd_names(Cs)

Returns a list of commands (function calls) generated in the Cmnd sequence, without Module, Arguments and other details.

init_per_suite(Config)

Initializes and extends Config for property based testing.

num_calls(Cs)

Returns number of command calls in a test case.

present_result(Module, Cmds, Triple, Config)

Equivalent to present_result(Module, Cmds, Triple, Config, []).

present_result(Module, Cmds, Triple, Config, Options0)

Presents the result of stateful (statem) property testing using the aggregate function in PropEr, QuickCheck or other similar property testing tool.

quickcheck(Property, Config)

Calls the selected tool's function for running the Property. It is usually and by historical reasons called quickcheck, and that is why that name is used in this module (ct_property_test).

sequential_parallel(Cs)

Returns a list with information about sequential and parallel parts.

Types

arguments()

(not exported) (since OTP 17.3)

-type arguments() :: [term()].

command()

(not exported) (since OTP 17.3)

-type command() :: set_command() | init_command().

command_list()

(not exported) (since OTP 17.3)

-type command_list() :: [command()].

dynamic_state()

(not exported) (since OTP 17.3)

-type dynamic_state() :: term().

function_name()

(not exported) (since OTP 17.3)

-type function_name() :: atom().

history()

(not exported) (since OTP 17.3)

-type history() :: [term()].

init_command()

(not exported) (since OTP 17.3)

-type init_command() :: {init, symbolic_state()}.

parallel_testcase()

(not exported) (since OTP 17.3)

-type parallel_testcase() :: {command_list(), [command_list()]}.

set_command()

(not exported) (since OTP 17.3)

-type set_command() :: {set, symbolic_var(), symbolic_call()}.

statem_result()

(not exported) (since OTP 17.3)

-type statem_result() :: ok | term().

symbolic_call()

(not exported) (since OTP 17.3)

-type symbolic_call() :: {call, module(), function_name(), arguments()}.

symbolic_state()

(not exported) (since OTP 17.3)

-type symbolic_state() :: term().

symbolic_var()

(not exported) (since OTP 17.3)

-type symbolic_var() :: {var, pos_integer()}.

Functions

cmnd_names(Cs)

(since OTP 27.1)

-spec cmnd_names(Cs) -> Result
                    when Cs :: command_list() | parallel_testcase(), Result :: [function_name()].

Returns a list of commands (function calls) generated in the Cmnd sequence, without Module, Arguments and other details.

For more information see: present_result/5.

init_per_suite(Config)

(since OTP 17.3)

-spec init_per_suite(Config) -> Config | {skip, Reason} | {fail, Reason}
                        when Config :: proplists:proplist(), Reason :: string().

Initializes and extends Config for property based testing.

This function investigates if support is available for either QuickCheck, PropEr or Triq and compiles the properties with the first tool found. It is supposed to be called in the init_per_suite/1 function in a CommonTest test suite.

Which tools to check for, and in which order could be set with the option {prop_tools, list(eqc|proper|triq)} in the CommonTest configuration Config. The default value is [eqc, proper, triq] with eqc being the first one searched for.

If no support is found for any tool, this function returns {skip, Explanation}.

In case of other errors, this function returns {fail, Explanation}.

If support is found, the option {property_test_tool,ToolModule} with the selected tool main module name (eqc, proper or triq) is added to the list Config which then is returned.

The property tests are assumed to be in a subdirectory named property_test. All found Erlang files in that directory are compiled with one of the macros 'EQC', 'PROPER' or 'TRIQ' set, depending on which tool that is first found. This could make parts of the Erlang property tests code to be included or excluded with the macro directives -ifdef(Macro). or -ifndef(Macro)..

The file(s) in the property_test subdirectory could, or should, include the ct_property_test include file:

-include_lib("common_test/include/ct_property_test.hrl").

This included file will:

Include the correct tool's include file

Set the macro 'MOD_eqc' to the correct module name for the selected tool. That is, the macro 'MOD_eqc' is set to either eqc, proper or triq.

num_calls(Cs)

(since OTP 27.1)

-spec num_calls(Cs) -> Result
                   when Cs :: command_list() | parallel_testcase(), Result :: [non_neg_integer()].

Returns number of command calls in a test case.

For more information see: present_result/5.

present_result(Module, Cmds, Triple, Config)

(since OTP 22.3)

-spec present_result(Module, Cmds, Triple, Config) -> boolean()
                        when
                            Module :: module(),
                            Cmds :: command_list() | parallel_testcase(),
                            Triple :: {H, Sf, Result},
                            H :: history(),
                            Sf :: dynamic_state(),
                            Result :: statem_result(),
                            Config :: proplists:proplist().

Equivalent to present_result(Module, Cmds, Triple, Config, []).

present_result(Module, Cmds, Triple, Config, Options0)

(since OTP 22.3)

-spec present_result(Module, Cmds, Triple, Config, Options0) -> boolean()
                        when
                            Module :: module(),
                            Cmds :: command_list() | parallel_testcase(),
                            Triple :: {H, Sf, Result},
                            H :: history(),
                            Sf :: dynamic_state(),
                            Result :: statem_result(),
                            Config :: proplists:proplist(),
                            Options0 :: proplists:proplist().

Presents the result of stateful (statem) property testing using the aggregate function in PropEr, QuickCheck or other similar property testing tool.

It is assumed to be called inside the property called by quickcheck/2:

...
RunResult = run_parallel_commands(?MODULE, Cmds),
ct_property_test:present_result(?MODULE, Cmds, RunResult, Config)
...

See the User's Guide for an example of the usage and of the default printout.

The StatisticsSpec is a list of the tuples:

{Title::string(), CollectFun::fun/1}

{Title::string(), FrequencyFun::/0, CollectFun::fun/1}

Each tuple will produce one table in the order of their places in the list.

Title will be the title of one result table

CollectFun is called with one argument: the Cmds. It should return a list of the values to be counted. The following pre-defined functions exist:

ct_property_test:cmnd_names/1 returns a list of commands (function calls) generated in the Cmnd sequence, without Module, Arguments and other details.

ct_property_test:num_calls/1 returns a list of the length of commands lists

ct_property_test:sequential_parallel/1 returns a list with information about sequential and parallel parts from Tool:parallel_commands/1,2

FrequencyFun/0 returns a fun/1 which is supposed to take a list of items as input, and return an iolist which will be printed as the table. Per default, the number of each item is counted and the percentage is printed for each. The list [a,b,a,a,c] could for example return

["a 60%\n","b 20%\n","c 20%\n"]

which will be printed by the print_fun. The default print_fun will print it as:

a 60%
b 20%
c 20%

The default StatisticsSpec is:

For sequential commands:

[{"Function calls", fun cmnd_names/1},
 {"Length of command sequences", fun print_frequency_ranges/0,
                                                  fun num_calls/1}]

For parallel commands:

[{"Distribution sequential/parallel", fun sequential_parallel/1},
 {"Function calls", fun cmnd_names/1},
 {"Length of command sequences", fun print_frequency_ranges/0,
                                                  fun num_calls/1}]

quickcheck(Property, Config)

(since OTP 17.3)

-spec quickcheck(Property, Config) -> true | {fail, Reason}
                    when Property :: term(), Config :: proplists:proplist(), Reason :: term().

Calls the selected tool's function for running the Property. It is usually and by historical reasons called quickcheck, and that is why that name is used in this module (ct_property_test).

The result is returned in a form suitable for Common Test test suites.

This function is intended to be called in test cases in test suites.

sequential_parallel(Cs)

(since OTP 27.1)

-spec sequential_parallel(Cs) -> Result
                             when Cs :: command_list() | parallel_testcase(), Result :: [atom()].

Returns a list with information about sequential and parallel parts.

For more information see: present_result/5.

ct_rpc

Common Test specific layer on Erlang/OTP rpc.

Summary

Functions

app_node(App, Candidates)

From a set of candidate nodes determines which of them is running the application App. If none of the candidate nodes is running App, the function makes the test case calling this function to fail. This function is the same as calling app_node(App, Candidates, true).

app_node(App, Candidates, FailOnBadRPC)

Same as ct_rpc:app_node/2, except that argument FailOnBadRPC determines if the search for a candidate node is to stop if badrpc is received at some point.

app_node(App, Candidates, FailOnBadRPC, Cookie)

Same as ct_rpc:app_node/2, except that argument FailOnBadRPC determines if the search for a candidate node is to stop if badrpc is received at some point.

call(Node, Module, Function, Args)

Equivalent to call(Node, Module, Function, Args, infinity, []).

call(Node, Module, Function, Args, TimeOut)

Evaluates apply(Module, Function, Args) on the node Node. Returns either whatever Function returns, or {badrpc, Reason} if the remote procedure call fails. If Node is {Fun, FunArgs}, applying Fun to FunArgs is to return a node name.

call(Node, Module, Function, Args, TimeOut, Cookie)

Evaluates apply(Module, Function, Args) on the node Node. Returns either whatever Function returns, or {badrpc, Reason} if the remote procedure call fails. If Node is {Fun, FunArgs}, applying Fun to FunArgs is to return a node name.

cast(Node, Module, Function, Args)

Evaluates apply(Module, Function, Args) on the node Node. No response is delivered and the process that makes the call is not suspended until the evaluation is completed as in the case of call/3,4. If Node is {Fun, FunArgs}, applying Fun to FunArgs is to return a node name.

cast(Node, Module, Function, Args, Cookie)

Evaluates apply(Module, Function, Args) on the node Node. No response is delivered and the process that makes the call is not suspended until the evaluation is completed as in the case of call/3,4. If Node is {Fun, FunArgs}, applying Fun to FunArgs is to return a node name.

Functions

app_node(App, Candidates)

-spec app_node(App, Candidates) -> CandidateNode
                  when App :: atom(), Candidates :: [node()], CandidateNode :: node().

From a set of candidate nodes determines which of them is running the application App. If none of the candidate nodes is running App, the function makes the test case calling this function to fail. This function is the same as calling app_node(App, Candidates, true).

app_node(App, Candidates, FailOnBadRPC)

-spec app_node(App, Candidates, FailOnBadRPC) -> CandidateNode
                  when
                      App :: atom(),
                      Candidates :: [node()],
                      FailOnBadRPC :: boolean(),
                      CandidateNode :: node().

Same as ct_rpc:app_node/2, except that argument FailOnBadRPC determines if the search for a candidate node is to stop if badrpc is received at some point.

app_node(App, Candidates, FailOnBadRPC, Cookie)

-spec app_node(App, Candidates, FailOnBadRPC, Cookie) -> CandidateNode
                  when
                      App :: atom(),
                      Candidates :: [node()],
                      FailOnBadRPC :: boolean(),
                      Cookie :: atom() | [],
                      CandidateNode :: node().

Same as ct_rpc:app_node/2, except that argument FailOnBadRPC determines if the search for a candidate node is to stop if badrpc is received at some point.

The cookie on the client node is set to Cookie for this rpc operation (used to match the server node cookie).

call(Node, Module, Function, Args)

-spec call(Node, Module, Function, Args) -> term() | {badrpc, Reason}
              when
                  Node :: {Function, Args} | node(),
                  Module :: module(),
                  Function :: atom(),
                  Args :: list(),
                  Reason :: term().

Equivalent to call(Node, Module, Function, Args, infinity, []).

call(Node, Module, Function, Args, TimeOut)

-spec call(Node, Module, Function, Args, TimeOut) -> term() | {badrpc, Reason}
              when
                  Node :: {Function, Args} | node(),
                  Module :: module(),
                  Function :: atom(),
                  Args :: list(),
                  TimeOut :: timeout(),
                  Reason :: term().

Evaluates apply(Module, Function, Args) on the node Node. Returns either whatever Function returns, or {badrpc, Reason} if the remote procedure call fails. If Node is {Fun, FunArgs}, applying Fun to FunArgs is to return a node name.

call(Node, Module, Function, Args, TimeOut, Cookie)

-spec call(Node, Module, Function, Args, TimeOut, Cookie) -> term() | {badrpc, Reason}
              when
                  Node :: {Function, Args} | node(),
                  Module :: module(),
                  Function :: atom(),
                  Args :: list(),
                  TimeOut :: timeout(),
                  Cookie :: atom() | [],
                  Reason :: term().

Evaluates apply(Module, Function, Args) on the node Node. Returns either whatever Function returns, or {badrpc, Reason} if the remote procedure call fails. If Node is {Fun, FunArgs}, applying Fun to FunArgs is to return a node name.

The cookie on the client node is set to Cookie for this rpc operation (used to match the server node cookie).

cast(Node, Module, Function, Args)

-spec cast(Node, Module, Function, Args) -> ok
              when
                  Node :: {Function, Args} | node(),
                  Module :: module(),
                  Function :: atom(),
                  Args :: list().

Evaluates apply(Module, Function, Args) on the node Node. No response is delivered and the process that makes the call is not suspended until the evaluation is completed as in the case of call/3,4. If Node is {Fun, FunArgs}, applying Fun to FunArgs is to return a node name.

cast(Node, Module, Function, Args, Cookie)

-spec cast(Node, Module, Function, Args, Cookie) -> ok
              when
                  Node :: {Function, Args} | node(),
                  Module :: module(),
                  Function :: atom(),
                  Args :: list(),
                  Cookie :: atom() | [].

Evaluates apply(Module, Function, Args) on the node Node. No response is delivered and the process that makes the call is not suspended until the evaluation is completed as in the case of call/3,4. If Node is {Fun, FunArgs}, applying Fun to FunArgs is to return a node name.

The cookie on the client node is set to Cookie for this rpc operation (used to match the server node cookie).

ct_slave

Common Test framework functions for starting and stopping nodes for Large-Scale Testing.

This module exports functions used by the Common Test Master to start and stop "slave" nodes. It is the default callback module for the {init, node_start} term in the Test Specification.

Summary

Types

start_options()

Options used for starting ct_slave node.

stop_options()

Options used for stopping ct_slave node.

Functions

start(Node) deprecated

Starts an Erlang node with name Node on the local host.

start(HostOrNode, NodeOrOpts) deprecated

Starts an Erlang node with default options on a specified host, or on the local host with specified options. That is, the call is interpreted as start(Host, Node) when the second argument is atom-valued and start(Node, Opts) when it is list-valued.

start(Host, Node, Opts) deprecated

Starts an Erlang node with name Node on host Host as specified by the combination of options in Opts.

stop(Node) deprecated

Stops the running Erlang node with name Node on the local host.

stop(HostOrNode, NodeOrOpts) deprecated

Stops the running Erlang node with name Node on host Host.

Types

start_options()

(since OTP R14B)

-type start_options() ::
          [{username, string()} |
           {password, string()} |
           {boot_timeout, non_neg_integer()} |
           {init_timeout, non_neg_integer()} |
           {startup_timeout, non_neg_integer()} |
           {startup_functions, [mfa()]} |
           {monitor_master, boolean()} |
           {kill_if_fail, boolean()} |
           {erl_flags, string()} |
           {env, [{Name :: os:env_var_name(), Val :: os:env_var_value() | false}]} |
           {ssh_port, inet:port_number()} |
           {ssh_opts, ssh:client_options()}].

Options used for starting ct_slave node.

stop_options()

(since OTP R14B)

-type stop_options() :: [{stop_timeout, non_neg_integer()}].

Options used for stopping ct_slave node.

Functions

start(Node)

(since OTP R14B)

This function is deprecated. ct_slave:start/1 is deprecated; use ?CT_PEER(), or the 'peer' module instead.

-spec start(Node) -> ok | {error, Reason, Node} when Node :: node(), Reason :: atom().

Starts an Erlang node with name Node on the local host.

See also ct_slave:start/3.

start(HostOrNode, NodeOrOpts)

(since OTP R14B)

This function is deprecated. ct_slave:start/2 is deprecated; use ?CT_PEER(), or the 'peer' module instead.

-spec start(HostOrNode, NodeOrOpts) -> ok | {error, Reason, Node}
               when
                   HostOrNode :: atom() | node(),
                   NodeOrOpts :: node() | start_options(),
                   Reason :: atom(),
                   Node :: node().

Starts an Erlang node with default options on a specified host, or on the local host with specified options. That is, the call is interpreted as start(Host, Node) when the second argument is atom-valued and start(Node, Opts) when it is list-valued.

See also ct_slave:start/3.

start(Host, Node, Opts)

(since OTP R14B)

This function is deprecated. ct_slave:start/3 is deprecated; use ?CT_PEER(), or the 'peer' module instead.

-spec start(Host, Node, Opts) -> ok | {error, Reason, Node}
               when Host :: atom(), Node :: node(), Opts :: start_options(), Reason :: atom().

Starts an Erlang node with name Node on host Host as specified by the combination of options in Opts.

Options Username and Password are used to log on to the remote host Host. Username, if omitted, defaults to the current username. Password is empty by default.

A list of functions specified in option Startup are executed after startup of the node. Notice that all used modules are to be present in the code path on Host.

The time-outs are applied as follows:

BootTimeout - The time to start the Erlang node, in seconds. Defaults to 3 seconds. If the node is not pingable within this time, the result {error, boot_timeout, NodeName} is returned.

InitTimeout - The time to wait for the node until it calls the internal callback function informing master about a successful startup. Defaults to 1 second. In case of a timed out message, the result {error, init_timeout, NodeName} is returned.

StartupTimeout - The time to wait until the node stops to run StartupFunctions. Defaults to 1 second. If this time-out occurs, the result {error, startup_timeout, NodeName} is returned.

Options:

monitor_master - Specifies if the slave node is to be stopped if the master node stops. Defaults to false.

kill_if_fail - Specifies if the slave node is to be killed if a time-out occurs during initialization or startup. Defaults to true. Notice that the node can also be still alive it the boot time-out occurred, but it is not killed in this case.

erl_flags - Specifies which flags are added to the parameters of the executable erl.

env - Specifies a list of environment variables that will extend the environment.

Special return values:

{error, already_started, NodeName} if the node with the specified name is already started on a specified host.

{error, started_not_connected, NodeName} if the node is started, but not connected to the master node.

{error, not_alive, NodeName} if the node on which ct_slave:start/3 is called, is not alive. Notice that NodeName is the name of the current node in this case.

stop(Node)

(since OTP R14B)

This function is deprecated. ct_slave:stop/1 is deprecated; use ?CT_PEER(), or the 'peer' module instead.

-spec stop(Node) -> {ok, Node} | {error, Reason, Node} when Node :: node(), Reason :: atom().

Stops the running Erlang node with name Node on the local host.

stop(HostOrNode, NodeOrOpts)

(since OTP R14B)

This function is deprecated. ct_slave:stop/2 is deprecated; use ?CT_PEER(), or the 'peer' module instead.

-spec stop(HostOrNode, NodeOrOpts) -> {ok, Node} | {error, Reason, Node}
              when
                  HostOrNode :: atom() | Node,
                  Node :: node(),
                  NodeOrOpts :: Node | stop_options(),
                  Reason :: atom().

Stops the running Erlang node with name Node on host Host.

ct_snmp

Common Test user interface module for the SNMP application.

The purpose of this module is to simplify SNMP configuration for the test case writer. Many test cases can use default values for common operations and then no SNMP configuration files need to be supplied. When it is necessary to change particular configuration parameters, a subset of the relevant SNMP configuration files can be passed to ct_snmp by Common Test configuration files. For more specialized configuration parameters, a simple SNMP configuration file can be placed in the test suite data directory. To simplify the test suite, Common Test keeps track of some of the SNMP manager information. This way the test suite does not have to handle as many input parameters as if it had to interface wthe OTP SNMP manager directly.

Configurable SNMP Manager and Agent Parameters:

Manager configuration:

[{start_manager, boolean()} - Optional. Default is true.

{users, [{user_name(), [call_back_module(), user_data()]}]} - Optional.

{usm_users, [{usm_user_name(), [usm_config()]}]} - Optional. SNMPv3 only.

{managed_agents,[{agent_name(), [user_name(), agent_ip(), agent_port(), [agent_config()]]}]} - managed_agents is optional.

{max_msg_size, integer()} - Optional. Default is 484.

{mgr_port, integer()} - Optional. Default is 5000.

{engine _id, string()} - Optional. Default is "mgrEngine".

Agent configuration:

{start_agent, boolean()} - Optional. Default is false.

{agent_sysname, string()} - Optional. Default is "ct_test".

{agent_manager_ip, manager_ip()} - Optional. Default is localhost.

{agent_vsns, list()} - Optional. Default is [v2].

{agent_trap_udp, integer()} - Optional. Default is 5000.

{agent_udp, integer()} - Optional. Default is 4000.

{agent_notify_type, atom()} - Optional. Default is trap.

{agent_sec_type, sec_type()} - Optional. Default is none.

{agent_passwd, string()} - Optional. Default is "".

{agent_engine_id, string()} - Optional. Default is "agentEngine".

{agent_max_msg_size, string()} - Optional. Default is 484.

The following parameters represents the SNMP configuration files context.conf, standard.conf, community.conf, vacm.conf, usm.conf, notify.conf, target_addr.conf, and target_params.conf. Notice that all values in agent.conf can be modified by the parameters listed above. All these configuration files have default values set by the SNMP application. These values can be overridden by suppling a list of valid configuration values or a file located in the test suites data directory, which can produce a list of valid configuration values if you apply function file:consult/1 to the file.

{agent_contexts, [term()] | {data_dir_file, rel_path()}} - Optional.

{agent_community, [term()] | {data_dir_file, rel_path()}} - Optional.

{agent_sysinfo, [term()] | {data_dir_file, rel_path()}} - Optional.

{agent_vacm, [term()] | {data_dir_file, rel_path()}} - Optional.

{agent_usm, [term()] | {data_dir_file, rel_path()}} - Optional.

{agent_notify_def, [term()] | {data_dir_file, rel_path()}} - Optional.

{agent_target_address_def, [term()] | {data_dir_file, rel_path()}} - Optional.

{agent_target_param_def, [term()] | {data_dir_file, rel_path()}} - Optional.

Parameter MgrAgentConfName in the functions is to be a name you allocate in your test suite using a require statement. Example (where MgrAgentConfName = snmp_mgr_agent):

suite() -> [{require, snmp_mgr_agent, snmp}].

or

ct:require(snmp_mgr_agent, snmp).

Notice that USM users are needed for SNMPv3 configuration and are not to be confused with users.

SNMP traps, inform, and report messages are handled by the user callback module. For details, see the SNMP application.

It is recommended to use the .hrl files created by the Erlang/OTP MIB compiler to define the Object Identifiers (OIDs). For example, to get the Erlang node name from erlNodeTable in the OTP-MIB:

Oid = ?erlNodeEntry ++ [?erlNodeName, 1]

Furthermore, values can be set for SNMP application configuration parameters, config, server, net_if, and so on (for a list of valid parameters and types, see the User's Guide for the SNMP application). This is done by defining a configuration data variable on the following form:

{snmp_app, [{manager, [snmp_app_manager_params()]},
            {agent, [snmp_app_agent_params()]}]}.

A name for the data must be allocated in the suite using require (see the example above). Pass this name as argument SnmpAppConfName to ct_snmp:start/3. ct_snmp specifies default values for some SNMP application configuration parameters (such as {verbosity,trace} for parameter config). This set of defaults is merged with the parameters specified by the user. The user values override ct_snmp defaults.

Summary

Types

agent_config()

agent_ip()

agent_name()

agent_port()

call_back_module()

error_index()

error_status()

ip()

manager_ip()

oid()

oids()

rel_path()

sec_type()

snmp_app_agent_params()

snmp_app_manager_params()

snmpreply()

user_data()

user_name()

usm_config()

usm_user_name()

value_type()

var_and_val()

varbind()

varbinds()

varsandvals()

These data types are described in the documentation for the SNMP application.

Functions

get_next_values(Agent, Oids, MgrAgentConfName)

Issues a synchronous SNMP get next request.

get_values(Agent, Oids, MgrAgentConfName)

Issues a synchronous SNMP get request.

load_mibs(Mibs)

Loads the MIBs into agent snmp_master_agent.

register_agents(MgrAgentConfName, ManagedAgents)

Explicitly instructs the manager to handle this agent. Corresponds to making an entry in agents.conf.

register_users(MgrAgentConfName, Users)

Registers the manager entity (=user) responsible for specific agent(s). Corresponds to making an entry in users.conf.

register_usm_users(MgrAgentConfName, UsmUsers)

Explicitly instructs the manager to handle this USM user. Corresponds to making an entry in usm.conf.

set_info(Config)

Returns a list of all successful set requests performed in the test case in reverse order. The list contains the involved user and agent, the value before set, and the new value. This is intended to simplify the cleanup in function end_per_testcase, that is, the undoing of the set requests and their possible side-effects.

set_values(Agent, VarsAndVals, MgrAgentConfName, Config)

Issues a synchronous SNMP set request.

start(Config, MgrAgentConfName)

Equivalent to start(Config, MgrAgentConfName, undefined).

start(Config, MgrAgentConfName, SnmpAppConfName)

Starts an SNMP manager and/or agent. In the manager case, registrations of users and agents, as specified by the configuration MgrAgentConfName, are performed. When using SNMPv3, called USM users are also registered. Users, usm_users, and managed agents can also be registered later using ct_snmp:register_users/2, ct_snmp:register_agents/2, and ct_snmp:register_usm_users/2.

stop(Config)

Stops the SNMP manager and/or agent, and removes all files created.

unload_mibs(Mibs)

Unloads the MIBs from agent snmp_master_agent.

unregister_agents(MgrAgentConfName)

Unregisters all managed agents.

unregister_agents(MgrAgentConfName, ManagedAgents)

Unregisters the specified managed agents.

unregister_users(MgrAgentConfName)

Unregisters all users.

unregister_users(MgrAgentConfName, Users)

Unregisters the specified users.

unregister_usm_users(MgrAgentConfName)

Unregisters all USM users.

unregister_usm_users(MgrAgentConfName, UsmUsers)

Unregisters the specified USM users.

Types

agent_config()

-type agent_config() :: {Item :: term(), Value :: term()}.

agent_ip()

-type agent_ip() :: ip().

agent_name()

-type agent_name() :: atom().

agent_port()

-type agent_port() :: integer().

call_back_module()

-type call_back_module() :: atom().

error_index()

-type error_index() :: integer().

error_status()

-type error_status() :: noError | atom().

ip()

-type ip() :: string() | {integer(), integer(), integer(), integer()}.

manager_ip()

-type manager_ip() :: ip().

oid()

-type oid() :: [byte()].

oids()

-type oids() :: [oid()].

rel_path()

-type rel_path() :: string().

sec_type()

-type sec_type() :: none | minimum | semi.

snmp_app_agent_params()

-type snmp_app_agent_params() :: term().

snmp_app_manager_params()

-type snmp_app_manager_params() :: term().

snmpreply()

-type snmpreply() :: {error_status(), error_index(), varbinds()}.

user_data()

-type user_data() :: term().

user_name()

-type user_name() :: atom().

usm_config()

-type usm_config() :: {Item :: term(), Value :: term()}.

usm_user_name()

-type usm_user_name() :: string().

value_type()

-type value_type() :: o | i | u | g | s.

var_and_val()

-type var_and_val() :: {oid(), value_type(), term()}.

varbind()

-type varbind() :: term().

varbinds()

-type varbinds() :: [varbind()].

varsandvals()

-type varsandvals() :: [var_and_val()].

These data types are described in the documentation for the SNMP application.

Functions

get_next_values(Agent, Oids, MgrAgentConfName)

-spec get_next_values(Agent, Oids, MgrAgentConfName) -> SnmpReply
                         when
                             Agent :: agent_name(),
                             Oids :: oids(),
                             MgrAgentConfName :: atom(),
                             SnmpReply :: snmpreply().

Issues a synchronous SNMP get next request.

get_values(Agent, Oids, MgrAgentConfName)

-spec get_values(Agent, Oids, MgrAgentConfName) -> SnmpReply
                    when
                        Agent :: agent_name(),
                        Oids :: oids(),
                        MgrAgentConfName :: atom(),
                        SnmpReply :: snmpreply().

Issues a synchronous SNMP get request.

load_mibs(Mibs)

-spec load_mibs(Mibs) -> ok | {error, Reason}
                   when
                       Mibs :: [MibName],
                       MibName :: string(),
                       Reason :: {'load aborted at', MibName, InternalReason},
                       InternalReason :: already_loaded | term().

Loads the MIBs into agent snmp_master_agent.

register_agents(MgrAgentConfName, ManagedAgents)

-spec register_agents(MgrAgentConfName, ManagedAgents) -> ok | {error, Reason}
                         when
                             MgrAgentConfName :: atom(),
                             ManagedAgents :: [{AgentName, [Uid | AgentIp | AgentUdpPort | AgentConf]}],
                             AgentName :: agent_name(),
                             Uid :: snmpm:user_id(),
                             AgentIp :: agent_ip(),
                             AgentUdpPort :: inet:port_number(),
                             AgentConf :: [agent_config()],
                             Reason :: term().

Explicitly instructs the manager to handle this agent. Corresponds to making an entry in agents.conf.

This function tries to register the specified managed agents, without checking if any of them exist. To change a registered managed agent, the agent must first be unregistered.

register_users(MgrAgentConfName, Users)

-spec register_users(MgrAgentConfName, Users) -> ok | {error, Reason}
                        when
                            MgrAgentConfName :: atom(),
                            Users :: [{Id, [Module | Data]}],
                            Id :: snmpm:user_id(),
                            Module :: user_name(),
                            Data :: user_data(),
                            Reason :: term().

Registers the manager entity (=user) responsible for specific agent(s). Corresponds to making an entry in users.conf.

This function tries to register the specified users, without checking if any of them exist. To change a registered user, the user must first be unregistered.

register_usm_users(MgrAgentConfName, UsmUsers)

-spec register_usm_users(MgrAgentConfName, UsmUsers) -> ok | {error, Reason}
                            when
                                MgrAgentConfName :: atom(),
                                UsmUsers :: [{UsmUserName, UsmConfig}],
                                UsmUserName :: usm_user_name(),
                                UsmConfig :: [usm_config()],
                                Reason :: term().

Explicitly instructs the manager to handle this USM user. Corresponds to making an entry in usm.conf.

This function tries to register the specified users, without checking if any of them exist. To change a registered user, the user must first be unregistered.

set_info(Config)

-spec set_info(Config) -> [{Agent, OldVarsAndVals, NewVarsAndVals}]
                  when
                      Config :: proplists:proplist(),
                      Agent :: agent_name(),
                      OldVarsAndVals :: varsandvals(),
                      NewVarsAndVals :: varsandvals().

Returns a list of all successful set requests performed in the test case in reverse order. The list contains the involved user and agent, the value before set, and the new value. This is intended to simplify the cleanup in function end_per_testcase, that is, the undoing of the set requests and their possible side-effects.

set_values(Agent, VarsAndVals, MgrAgentConfName, Config)

-spec set_values(Agent, VarsAndVals, MgrAgentConfName, Config) -> SnmpReply
                    when
                        Agent :: agent_name(),
                        VarsAndVals :: varsandvals(),
                        MgrAgentConfName :: atom(),
                        Config :: proplists:proplist(),
                        SnmpReply :: snmpreply().

Issues a synchronous SNMP set request.

start(Config, MgrAgentConfName)

-spec start(Config, MgrAgentConfName) -> ok | {error, Reason}
               when Config :: proplists:proplist(), MgrAgentConfName :: atom(), Reason :: term().

Equivalent to start(Config, MgrAgentConfName, undefined).

start(Config, MgrAgentConfName, SnmpAppConfName)

-spec start(Config, MgrAgentConfName, SnmpAppConfName) -> ok | {error, Reason}
               when
                   Config :: proplists:proplist(),
                   MgrAgentConfName :: atom(),
                   SnmpAppConfName :: atom(),
                   Reason :: term().

Starts an SNMP manager and/or agent. In the manager case, registrations of users and agents, as specified by the configuration MgrAgentConfName, are performed. When using SNMPv3, called USM users are also registered. Users, usm_users, and managed agents can also be registered later using ct_snmp:register_users/2, ct_snmp:register_agents/2, and ct_snmp:register_usm_users/2.

The agent started is called snmp_master_agent. Use ct_snmp:load_mibs/1 to load MIBs into the agent.

With SnmpAppConfName SNMP applications can be configured with parameters config, mibs, net_if, and so on. The values are merged with (and possibly override) default values set by ct_snmp.

stop(Config)

-spec stop(Config) -> ok when Config :: proplists:proplist().

Stops the SNMP manager and/or agent, and removes all files created.

unload_mibs(Mibs)

(since OTP R16B)

-spec unload_mibs(Mibs) -> ok | {error, Reason}
                     when
                         Mibs :: [MibName],
                         MibName :: string(),
                         Reason :: {'unload aborted at', MibName, InternalReason},
                         InternalReason :: not_loaded | term().

Unloads the MIBs from agent snmp_master_agent.

unregister_agents(MgrAgentConfName)

-spec unregister_agents(MgrAgentConfName) -> ok when MgrAgentConfName :: atom().

Unregisters all managed agents.

unregister_agents(MgrAgentConfName, ManagedAgents)

(since OTP R16B)

-spec unregister_agents(MgrAgentConfName, ManagedAgents) -> ok
                           when MgrAgentConfName :: atom(), ManagedAgents :: [agent_name()].

Unregisters the specified managed agents.

unregister_users(MgrAgentConfName)

-spec unregister_users(MgrAgentConfName) -> ok when MgrAgentConfName :: atom().

Unregisters all users.

unregister_users(MgrAgentConfName, Users)

(since OTP R16B)

-spec unregister_users(MgrAgentConfName, Users) -> ok
                          when MgrAgentConfName :: atom(), Users :: [snmpm:user_id()].

Unregisters the specified users.

unregister_usm_users(MgrAgentConfName)

(since OTP R16B)

-spec unregister_usm_users(MgrAgentConfName) -> ok when MgrAgentConfName :: atom().

Unregisters all USM users.

unregister_usm_users(MgrAgentConfName, UsmUsers)

(since OTP R16B)

-spec unregister_usm_users(MgrAgentConfName, UsmUsers) -> ok
                              when MgrAgentConfName :: atom(), UsmUsers :: [usm_user_name()].

Unregisters the specified USM users.

ct_ssh

SSH/SFTP client module.

This module uses application SSH, which provides detailed information about, for example, functions, types, and options.

Argument Server in the SFTP functions is only to be used for SFTP sessions that have been started on existing SSH connections (that is, when the original connection type is ssh). Whenever the connection type is sftp, use the SSH connection reference only.

The following options are valid for specifying an SSH/SFTP connection (that is, can be used as configuration elements):

[{ConnType, Addr},
 {port, Port},
 {user, UserName}
 {password, Pwd}
 {user_dir, String}
 {public_key_alg, PubKeyAlg}
 {connect_timeout, Timeout}
 {key_cb, KeyCallbackMod}]

ConnType = ssh | sftp.

For other types, see ssh.

All time-out parameters in ct_ssh functions are values in milliseconds.

Summary

Types

connection()

Reference to opened SSH/SFTP connection associated to either a handle or target_name.

connection_type()

Connection type used for connect.

handle()

Handle for a specific SSH/SFTP connection, see module ct.

ssh_channel_id()

Data type representing a channel inside a connection.

ssh_data_type_code()

The valid values are 0 ("normal") and 1 ("stderr"), see RFC 4254, Section 5.2.

Functions

apread(SSH, Handle, Position, Length)

For information and other types, see ssh_sftp.

apread(SSH, Server, Handle, Position, Length)

For information and other types, see ssh_sftp.

apwrite(SSH, Handle, Position, Data)

For information and other types, see ssh_sftp.

apwrite(SSH, Server, Handle, Position, Data)

For information and other types, see ssh_sftp.

aread(SSH, Handle, Len)

For information and other types, see ssh_sftp.

aread(SSH, Server, Handle, Len)

For information and other types, see ssh_sftp.

awrite(SSH, Handle, Data)

For information and other types, see ssh_sftp.

awrite(SSH, Server, Handle, Data)

For information and other types, see ssh_sftp.

close(SSH, Handle)

For information and other types, see ssh_sftp.

close(SSH, Server, Handle)

For information and other types, see ssh_sftp.

connect(KeyOrName)

Equivalent to connect(KeyOrName, host, []).

connect/2

Opens an SSH or SFTP connection using the information associated with KeyOrName (see connect/3).

connect(KeyOrName, ConnType, ExtraOpts)

Opens an SSH or SFTP connection using the information associated with KeyOrName.

del_dir(SSH, Name)

For information and other types, see ssh_sftp.

del_dir(SSH, Server, Name)

For information and other types, see ssh_sftp.

delete(SSH, Name)

For information and other types, see ssh_sftp.

delete(SSH, Server, Name)

For information and other types, see ssh_sftp.

disconnect(SSH)

Closes an SSH/SFTP connection.

exec(SSH, Command)

Equivalent to exec(SSH, Command, DefaultTimeout).

exec/3

Requests server to perform Command, (see exec/4).

exec(SSH, ChannelId, Command, Timeout)

Requests server to perform Command. A previously opened session channel is used for the request. Data is received from the server as a result of the command.

get_file_info(SSH, Handle)

For information and other types, see ssh_sftp.

get_file_info(SSH, Server, Handle)

For information and other types, see ssh_sftp.

list_dir(SSH, Path)

For information and other types, see ssh_sftp.

list_dir(SSH, Server, Path)

For information and other types, see ssh_sftp.

make_dir(SSH, Name)

For information and other types, see ssh_sftp.

make_dir(SSH, Server, Name)

For information and other types, see ssh_sftp.

make_symlink(SSH, Name, Target)

For information and other types, see ssh_sftp.

make_symlink(SSH, Server, Name, Target)

For information and other types, see ssh_sftp.

open(SSH, File, Mode)

For information and other types, see ssh_sftp.

open(SSH, Server, File, Mode)

For information and other types, see ssh_sftp.

opendir(SSH, Path)

For information and other types, see ssh_sftp.

opendir(SSH, Server, Path)

For information and other types, see ssh_sftp.

position(SSH, Handle, Location)

For information and other types, see ssh_sftp.

position(SSH, Server, Handle, Location)

For information and other types, see ssh_sftp.

pread(SSH, Handle, Position, Length)

For information and other types, see ssh_sftp.

pread(SSH, Server, Handle, Position, Length)

For information and other types, see ssh_sftp.

pwrite(SSH, Handle, Position, Data)

For information and other types, see ssh_sftp.

pwrite(SSH, Server, Handle, Position, Data)

For information and other types, see ssh_sftp.

read(SSH, Handle, Len)

For information and other types, see ssh_sftp.

read(SSH, Server, Handle, Len)

For information and other types, see ssh_sftp.

read_file(SSH, File)

For information and other types, see ssh_sftp.

read_file(SSH, Server, File)

For information and other types, see ssh_sftp.

read_file_info(SSH, Name)

For information and other types, see ssh_sftp.

read_file_info(SSH, Server, Name)

For information and other types, see ssh_sftp.

read_link(SSH, Name)

For information and other types, see ssh_sftp.

read_link(SSH, Server, Name)

For information and other types, see ssh_sftp.

read_link_info(SSH, Name)

For information and other types, see ssh_sftp.

read_link_info(SSH, Server, Name)

For information and other types, see ssh_sftp.

receive_response(SSH, ChannelId)

Equivalent to receive_response(SSH, ChannelId, close, DefaultTimeout).

receive_response/3

Receives expected data from server on the specified session channel (see receive_response/4).

receive_response(SSH, ChannelId, End, Timeout)

Receives expected data from server on the specified session channel.

rename(SSH, OldName, NewName)

For information and other types, see ssh_sftp.

rename(SSH, Server, OldName, NewName)

For information and other types, see ssh_sftp.

send(SSH, ChannelId, Data)

Equivalent to send(SSH, ChannelId, 0, Data, DefaultTimeout).

send/4

Sends data to server on specified session channel (see send/5).

send(SSH, ChannelId, Type, Data, Timeout)

Sends data to server on specified session channel.

send_and_receive(SSH, ChannelId, Data)

Equivalent to send_and_receive(SSH, ChannelId, 0, Data, close, DefaultTimeout).

send_and_receive/4

Sends data to server on specified session channel and waits to receive the server response (see send_and_receive/6).

send_and_receive/5

Sends data to server on specified session channel and waits to receive the server response (see send_and_receive/6).

send_and_receive(SSH, ChannelId, Type, Data, End, Timeout)

Sends data to server on specified session channel and waits to receive the server response.

session_close(SSH, ChannelId)

Closes an SSH session channel.

session_open(SSH)

Equivalent to session_open(SSH, DefaultTimeout).

session_open(SSH, Timeout)

Opens a channel for an SSH session.

sftp_connect(SSH)

Starts an SFTP session on an already existing SSH connection. Server identifies the new session and must be specified whenever SFTP requests are to be sent.

shell(SSH, ChannelId)

Equivalent to shell(SSH, ChannelId, DefaultTimeout).

shell(SSH, ChannelId, Timeout)

Requests that the user's default shell (typically defined in /etc/passwd in Unix systems) is executed at the server end.

subsystem(SSH, ChannelId, Subsystem)

Equivalent to subsystem(SSH, Channel, Subsystem, DefaultTimeout).

subsystem(SSH, ChannelId, Subsystem, Timeout)

Sends a request to execute a predefined subsystem.

write(SSH, Handle, Data)

For information and other types, see ssh_sftp.

write(SSH, Server, Handle, Data)

For information and other types, see ssh_sftp.

write_file(SSH, File, Iolist)

For information and other types, see ssh_sftp.

write_file(SSH, Server, File, Iolist)

For information and other types, see ssh_sftp.

write_file_info(SSH, Name, Info)

For information and other types, see ssh_sftp.

write_file_info(SSH, Server, Name, Info)

For information and other types, see ssh_sftp.

Types

connection()

(not exported)

-type connection() :: handle() | ct:target_name().

Reference to opened SSH/SFTP connection associated to either a handle or target_name.

connection_type()

(not exported)

-type connection_type() :: host | ssh | sftp.

Connection type used for connect.

handle()

(not exported)

-type handle() :: pid().

Handle for a specific SSH/SFTP connection, see module ct.

ssh_channel_id()

(not exported)

-type ssh_channel_id() :: non_neg_integer().

Data type representing a channel inside a connection.

"For ssh_channel_id, see module ssh.".

ssh_data_type_code()

(not exported)

-type ssh_data_type_code() :: non_neg_integer().

The valid values are 0 ("normal") and 1 ("stderr"), see RFC 4254, Section 5.2.

Functions

apread(SSH, Handle, Position, Length)

-spec apread(SSH, Handle, Position, Length) -> Result
                when
                    SSH :: connection(),
                    Handle :: term(),
                    Position :: integer(),
                    Length :: integer(),
                    Result :: {async, N} | {error, Reason},
                    N :: term(),
                    Reason :: term().

For information and other types, see ssh_sftp.

apread(SSH, Server, Handle, Position, Length)

-spec apread(SSH, Server, Handle, Position, Length) -> Result
                when
                    SSH :: connection(),
                    Server :: pid(),
                    Handle :: term(),
                    Position :: integer(),
                    Length :: integer(),
                    Result :: {async, N} | {error, Reason},
                    N :: term(),
                    Reason :: term().

For information and other types, see ssh_sftp.

apwrite(SSH, Handle, Position, Data)

-spec apwrite(SSH, Handle, Position, Data) -> Result
                 when
                     SSH :: connection(),
                     Handle :: term(),
                     Position :: integer(),
                     Data :: binary(),
                     Result :: {async, N} | {error, Reason},
                     N :: term(),
                     Reason :: term().

For information and other types, see ssh_sftp.

apwrite(SSH, Server, Handle, Position, Data)

-spec apwrite(SSH, Server, Handle, Position, Data) -> Result
                 when
                     SSH :: connection(),
                     Server :: pid(),
                     Handle :: term(),
                     Position :: integer(),
                     Data :: binary(),
                     Result :: {async, N} | {error, Reason},
                     N :: term(),
                     Reason :: term().

For information and other types, see ssh_sftp.

aread(SSH, Handle, Len)

-spec aread(SSH, Handle, Len) -> Result
               when
                   SSH :: connection(),
                   Handle :: term(),
                   Len :: integer(),
                   Result :: {async, N} | {error, Reason},
                   N :: term(),
                   Reason :: term().

For information and other types, see ssh_sftp.

aread(SSH, Server, Handle, Len)

-spec aread(SSH, Server, Handle, Len) -> Result
               when
                   SSH :: connection(),
                   Server :: pid(),
                   Handle :: term(),
                   Len :: integer(),
                   Result :: {async, N} | {error, Reason},
                   N :: term(),
                   Reason :: term().

For information and other types, see ssh_sftp.

awrite(SSH, Handle, Data)

-spec awrite(SSH, Handle, Data) -> Result
                when
                    SSH :: connection(),
                    Handle :: term(),
                    Data :: binary(),
                    Result :: {async, N} | {error, Reason},
                    N :: term(),
                    Reason :: term().

For information and other types, see ssh_sftp.

awrite(SSH, Server, Handle, Data)

-spec awrite(SSH, Server, Handle, Data) -> Result
                when
                    SSH :: connection(),
                    Server :: pid(),
                    Handle :: term(),
                    Data :: binary(),
                    Result :: {async, N} | {error, Reason},
                    N :: term(),
                    Reason :: term().

For information and other types, see ssh_sftp.

close(SSH, Handle)

-spec close(SSH, Handle) -> Result
               when
                   SSH :: connection(),
                   Handle :: term(),
                   Result :: ok | {error, Reason},
                   Reason :: term().

For information and other types, see ssh_sftp.

close(SSH, Server, Handle)

-spec close(SSH, Server, Handle) -> Result
               when
                   SSH :: connection(),
                   Server :: pid(),
                   Handle :: term(),
                   Result :: ok | {error, Reason},
                   Reason :: term().

For information and other types, see ssh_sftp.

connect(KeyOrName)

-spec connect(KeyOrName) -> {ok, Handle} | {error, Reason}
                 when KeyOrName :: ct:key_or_name(), Handle :: handle(), Reason :: term().

Equivalent to connect(KeyOrName, host, []).

connect/2

-spec connect(KeyOrName, ConnType) -> {ok, Handle} | {error, Reason}
                 when
                     KeyOrName :: ct:key_or_name(),
                     ConnType :: connection_type(),
                     Handle :: handle(),
                     Reason :: term();
             (KeyOrName, ExtraOpts) -> {ok, Handle} | {error, Reason}
                 when
                     KeyOrName :: ct:key_or_name(),
                     ExtraOpts :: [ExtraOption],
                     ExtraOption ::
                         {ssh, Address} | {sftp, Address} | ssh:client_option() | ssh_sftp:sftp_option(),
                     Address :: ssh:host(),
                     Handle :: handle(),
                     Reason :: term().

Opens an SSH or SFTP connection using the information associated with KeyOrName (see connect/3).

Equivalent to connect(KeyOrName, ConnType, []) if called with ConnType being atom.

Equivalent to connect(KeyOrName, host, ExtraOpts) if called with ExtraOpts being list.

connect(KeyOrName, ConnType, ExtraOpts)

-spec connect(KeyOrName, ConnType, ExtraOpts) -> {ok, Handle} | {error, Reason}
                 when
                     KeyOrName :: ct:key_or_name(),
                     ConnType :: connection_type(),
                     ExtraOpts :: [ExtraOption],
                     ExtraOption ::
                         {ssh, Address} | {sftp, Address} | ssh:client_option() | ssh_sftp:sftp_option(),
                     Address :: ssh:host(),
                     Handle :: handle(),
                     Reason :: term().

Opens an SSH or SFTP connection using the information associated with KeyOrName.

If Name (an alias name for Key) is used to identify the connection, this name can be used as connection reference for subsequent calls. Only one open connection at a time associated with Name is possible. If Key is used, the returned handle must be used for subsequent calls (multiple connections can be opened using the configuration data specified by Key).

For information on how to create a new Name, see ct:require/2.

ConnType always overrides the type specified in the address tuple in the configuration data (and in ExtraOpts). So it is possible to, for example, open an SFTP connection directly using data originally specifying an SSH connection. Value host means that the connection type specified by the host option (either in the configuration data or in ExtraOpts) is used.

ExtraOpts (optional) are extra SSH options to be added to the configuration data for KeyOrName. The extra options override any existing options with the same key in the configuration data. For details on valid SSH options, see application SSH.

del_dir(SSH, Name)

-spec del_dir(SSH, Name) -> Result
                 when
                     SSH :: connection(),
                     Name :: file:filename(),
                     Result :: ok | {error, Reason},
                     Reason :: term().

For information and other types, see ssh_sftp.

del_dir(SSH, Server, Name)

-spec del_dir(SSH, Server, Name) -> Result
                 when
                     SSH :: connection(),
                     Server :: pid(),
                     Name :: file:filename(),
                     Result :: ok | {error, Reason},
                     Reason :: term().

For information and other types, see ssh_sftp.

delete(SSH, Name)

-spec delete(SSH, Name) -> Result
                when
                    SSH :: connection(),
                    Name :: file:filename(),
                    Result :: ok | {error, Reason},
                    Reason :: term().

For information and other types, see ssh_sftp.

delete(SSH, Server, Name)

-spec delete(SSH, Server, Name) -> Result
                when
                    SSH :: connection(),
                    Server :: pid(),
                    Name :: file:filename(),
                    Result :: ok | {error, Reason},
                    Reason :: term().

For information and other types, see ssh_sftp.

disconnect(SSH)

-spec disconnect(SSH) -> ok | {error, Reason} when SSH :: connection(), Reason :: term().

Closes an SSH/SFTP connection.

exec(SSH, Command)

-spec exec(SSH, Command) -> {ok, Data} | {timeout, Data} | {error, Reason}
              when SSH :: connection(), Command :: string(), Data :: string(), Reason :: term().

Equivalent to exec(SSH, Command, DefaultTimeout).

exec/3

-spec exec(SSH, Command, Timeout) -> {ok, Data} | {timeout, Data} | {error, Reason}
              when
                  SSH :: connection(),
                  Command :: string(),
                  Timeout :: timeout(),
                  Data :: string(),
                  Reason :: term();
          (SSH, ChannelId, Command) -> {ok, Data} | {timeout, Data} | {error, Reason}
              when
                  SSH :: connection(),
                  ChannelId :: ssh_channel_id(),
                  Command :: string(),
                  Data :: string(),
                  Reason :: term().

Requests server to perform Command, (see exec/4).

Equivalent to exec(SSH, undefined, Command, Timeout) if called with Command being string.

Equivalent to exec(SSH, ChannelId, Command, DefaultTimeout) if called with ChannelId being integer.

exec(SSH, ChannelId, Command, Timeout)

-spec exec(SSH, ChannelId, Command, Timeout) -> {ok, Data} | {timeout, Data} | {error, Reason}
              when
                  SSH :: connection(),
                  ChannelId :: ssh_channel_id() | undefined,
                  Command :: string(),
                  Timeout :: timeout(),
                  Data :: string(),
                  Reason :: term().

Requests server to perform Command. A previously opened session channel is used for the request. Data is received from the server as a result of the command.

get_file_info(SSH, Handle)

-spec get_file_info(SSH, Handle) -> Result
                       when
                           SSH :: connection(),
                           Handle :: term(),
                           Result :: {ok, FileInfo} | {error, Reason},
                           FileInfo :: file:file_info(),
                           Reason :: term().

For information and other types, see ssh_sftp.

get_file_info(SSH, Server, Handle)

-spec get_file_info(SSH, Server, Handle) -> Result
                       when
                           SSH :: connection(),
                           Server :: pid(),
                           Handle :: term(),
                           Result :: {ok, FileInfo} | {error, Reason},
                           FileInfo :: file:file_info(),
                           Reason :: term().

For information and other types, see ssh_sftp.

list_dir(SSH, Path)

-spec list_dir(SSH, Path) -> Result
                  when
                      SSH :: connection(),
                      Path :: file:filename(),
                      Result :: {ok, FileNames} | {error, Reason},
                      FileNames :: [FileName],
                      FileName :: file:filename(),
                      Reason :: term().

For information and other types, see ssh_sftp.

list_dir(SSH, Server, Path)

-spec list_dir(SSH, Server, Path) -> Result
                  when
                      SSH :: connection(),
                      Server :: pid(),
                      Path :: file:filename(),
                      Result :: {ok, FileNames} | {error, Reason},
                      FileNames :: [FileName],
                      FileName :: file:filename(),
                      Reason :: term().

For information and other types, see ssh_sftp.

make_dir(SSH, Name)

-spec make_dir(SSH, Name) -> Result
                  when
                      SSH :: connection(),
                      Name :: file:filename(),
                      Result :: ok | {error, Reason},
                      Reason :: term().

For information and other types, see ssh_sftp.

make_dir(SSH, Server, Name)

-spec make_dir(SSH, Server, Name) -> Result
                  when
                      SSH :: connection(),
                      Server :: pid(),
                      Name :: file:filename(),
                      Result :: ok | {error, Reason},
                      Reason :: term().

For information and other types, see ssh_sftp.

make_symlink(SSH, Name, Target)

-spec make_symlink(SSH, Name, Target) -> Result
                      when
                          SSH :: connection(),
                          Name :: file:filename(),
                          Target :: file:filename(),
                          Result :: ok | {error, Reason},
                          Reason :: term().

For information and other types, see ssh_sftp.

make_symlink(SSH, Server, Name, Target)

-spec make_symlink(SSH, Server, Name, Target) -> Result
                      when
                          SSH :: connection(),
                          Server :: pid(),
                          Name :: file:filename(),
                          Target :: file:filename(),
                          Result :: ok | {error, Reason},
                          Reason :: term().

For information and other types, see ssh_sftp.

open(SSH, File, Mode)

-spec open(SSH, File, Mode) -> Result
              when
                  SSH :: connection(),
                  File :: file:filename(),
                  Mode :: [read | write | append | binary | raw],
                  Result :: {ok, Handle} | {error, Reason},
                  Handle :: term(),
                  Reason :: term().

For information and other types, see ssh_sftp.

open(SSH, Server, File, Mode)

-spec open(SSH, Server, File, Mode) -> Result
              when
                  SSH :: connection(),
                  Server :: pid(),
                  File :: file:filename(),
                  Mode :: [read | write | append | binary | raw],
                  Result :: {ok, Handle} | {error, Reason},
                  Handle :: term(),
                  Reason :: term().

For information and other types, see ssh_sftp.

opendir(SSH, Path)

-spec opendir(SSH, Path) -> Result
                 when
                     SSH :: connection(),
                     Path :: file:filename(),
                     Result :: {ok, Handle} | {error, Reason},
                     Handle :: term(),
                     Reason :: term().

For information and other types, see ssh_sftp.

opendir(SSH, Server, Path)

-spec opendir(SSH, Server, Path) -> Result
                 when
                     SSH :: connection(),
                     Server :: pid(),
                     Path :: file:filename(),
                     Result :: {ok, Handle} | {error, Reason},
                     Handle :: term(),
                     Reason :: term().

For information and other types, see ssh_sftp.

position(SSH, Handle, Location)

-spec position(SSH, Handle, Location) -> Result
                  when
                      SSH :: connection(),
                      Handle :: term(),
                      Location ::
                          Offset | {bof, Offset} | {cur, Offset} | {eof, Offset} | bof | cur | eof,
                      Offset :: integer(),
                      Result :: {ok, NewPosition} | {error, Reason},
                      NewPosition :: integer(),
                      Reason :: term().

For information and other types, see ssh_sftp.

position(SSH, Server, Handle, Location)

-spec position(SSH, Server, Handle, Location) -> Result
                  when
                      SSH :: connection(),
                      Server :: pid(),
                      Handle :: term(),
                      Location ::
                          Offset | {bof, Offset} | {cur, Offset} | {eof, Offset} | bof | cur | eof,
                      Offset :: integer(),
                      Result :: {ok, NewPosition} | {error, Reason},
                      NewPosition :: integer(),
                      Reason :: term().

For information and other types, see ssh_sftp.

pread(SSH, Handle, Position, Length)

-spec pread(SSH, Handle, Position, Length) -> Result
               when
                   SSH :: connection(),
                   Handle :: term(),
                   Position :: integer(),
                   Length :: integer(),
                   Result :: {ok, Data} | eof | {error, Reason},
                   Data :: string() | binary(),
                   Reason :: term().

For information and other types, see ssh_sftp.

pread(SSH, Server, Handle, Position, Length)

-spec pread(SSH, Server, Handle, Position, Length) -> Result
               when
                   SSH :: connection(),
                   Server :: pid(),
                   Handle :: term(),
                   Position :: integer(),
                   Length :: integer(),
                   Result :: {ok, Data} | eof | {error, Reason},
                   Data :: string() | binary(),
                   Reason :: term().

For information and other types, see ssh_sftp.

pwrite(SSH, Handle, Position, Data)

-spec pwrite(SSH, Handle, Position, Data) -> Result
                when
                    SSH :: connection(),
                    Handle :: term(),
                    Position :: integer(),
                    Data :: iolist(),
                    Result :: ok | {error, Reason},
                    Reason :: term().

For information and other types, see ssh_sftp.

pwrite(SSH, Server, Handle, Position, Data)

-spec pwrite(SSH, Server, Handle, Position, Data) -> Result
                when
                    SSH :: connection(),
                    Server :: pid(),
                    Handle :: term(),
                    Position :: integer(),
                    Data :: iolist(),
                    Result :: ok | {error, Reason},
                    Reason :: term().

For information and other types, see ssh_sftp.

read(SSH, Handle, Len)

-spec read(SSH, Handle, Len) -> Result
              when
                  SSH :: connection(),
                  Handle :: term(),
                  Len :: integer(),
                  Result :: {ok, Data} | eof | {error, Reason},
                  Data :: string() | binary(),
                  Reason :: term().

For information and other types, see ssh_sftp.

read(SSH, Server, Handle, Len)

-spec read(SSH, Server, Handle, Len) -> Result
              when
                  SSH :: connection(),
                  Server :: pid(),
                  Handle :: term(),
                  Len :: integer(),
                  Result :: {ok, Data} | eof | {error, Reason},
                  Data :: string() | binary(),
                  Reason :: term().

For information and other types, see ssh_sftp.

read_file(SSH, File)

-spec read_file(SSH, File) -> Result
                   when
                       SSH :: connection(),
                       File :: file:filename(),
                       Result :: {ok, Data} | {error, Reason},
                       Data :: binary(),
                       Reason :: term().

For information and other types, see ssh_sftp.

read_file(SSH, Server, File)

-spec read_file(SSH, Server, File) -> Result
                   when
                       SSH :: connection(),
                       Server :: pid(),
                       File :: file:filename(),
                       Result :: {ok, Data} | {error, Reason},
                       Data :: binary(),
                       Reason :: term().

For information and other types, see ssh_sftp.

read_file_info(SSH, Name)

-spec read_file_info(SSH, Name) -> Result
                        when
                            SSH :: connection(),
                            Name :: file:filename(),
                            Result :: {ok, FileInfo} | {error, Reason},
                            FileInfo :: file:file_info(),
                            Reason :: term().

For information and other types, see ssh_sftp.

read_file_info(SSH, Server, Name)

-spec read_file_info(SSH, Server, Name) -> Result
                        when
                            SSH :: connection(),
                            Server :: pid(),
                            Name :: file:filename(),
                            Result :: {ok, FileInfo} | {error, Reason},
                            FileInfo :: file:file_info(),
                            Reason :: term().

For information and other types, see ssh_sftp.

read_link(SSH, Name)

-spec read_link(SSH, Name) -> Result
                   when
                       SSH :: connection(),
                       Name :: file:filename(),
                       Result :: {ok, Target} | {error, Reason},
                       Target :: file:filename(),
                       Reason :: term().

For information and other types, see ssh_sftp.

read_link(SSH, Server, Name)

-spec read_link(SSH, Server, Name) -> Result
                   when
                       SSH :: connection(),
                       Server :: pid(),
                       Name :: file:filename(),
                       Result :: {ok, Target} | {error, Reason},
                       Target :: file:filename(),
                       Reason :: term().

For information and other types, see ssh_sftp.

read_link_info(SSH, Name)

-spec read_link_info(SSH, Name) -> Result
                        when
                            SSH :: connection(),
                            Name :: string(),
                            Result :: {ok, FileInfo} | {error, Reason},
                            FileInfo :: file:file_info(),
                            Reason :: term().

For information and other types, see ssh_sftp.

read_link_info(SSH, Server, Name)

-spec read_link_info(SSH, Server, Name) -> Result
                        when
                            SSH :: connection(),
                            Server :: pid(),
                            Name :: file:filename(),
                            Result :: {ok, FileInfo} | {error, Reason},
                            FileInfo :: file:file_info(),
                            Reason :: term().

For information and other types, see ssh_sftp.

receive_response(SSH, ChannelId)

-spec receive_response(SSH, ChannelId) -> {ok, Data} | {timeout, Data} | {error, Reason}
                          when
                              SSH :: connection(),
                              ChannelId :: ssh_channel_id(),
                              Data :: string(),
                              Reason :: term().

Equivalent to receive_response(SSH, ChannelId, close, DefaultTimeout).

receive_response/3

-spec receive_response(SSH, ChannelId, End) -> {ok, Data} | {timeout, Data} | {error, Reason}
                          when
                              SSH :: connection(),
                              ChannelId :: ssh_channel_id(),
                              End :: fun((string()) -> boolean()),
                              Data :: string(),
                              Reason :: term();
                      (SSH, ChannelId, Timeout) -> {ok, Data} | {timeout, Data} | {error, Reason}
                          when
                              SSH :: connection(),
                              ChannelId :: ssh_channel_id(),
                              Timeout :: timeout(),
                              Data :: string(),
                              Reason :: term().

Receives expected data from server on the specified session channel (see receive_response/4).

Equivalent to receive_response(SSH, ChannelId, End, DefaultTimeout) if called with End being function.

Equivalent to receive_response(SSH, ChannelId, close, Timeout) if called with Timeout being integer.

receive_response(SSH, ChannelId, End, Timeout)

-spec receive_response(SSH, ChannelId, End, Timeout) -> {ok, Data} | {timeout, Data} | {error, Reason}
                          when
                              SSH :: connection(),
                              ChannelId :: ssh_channel_id(),
                              End :: close | timeout | fun((string()) -> boolean()),
                              Timeout :: timeout(),
                              Data :: string(),
                              Reason :: term().

Receives expected data from server on the specified session channel.

If End == close, data is returned to the caller when the channel is closed by the server. If a time-out occurs before this happens, the function returns {timeout,Data} (where Data is the data received so far).

If End == timeout, a time-out is expected and {ok,Data} is returned both in the case of a time-out and when the channel is closed.

If End is a fun, this fun is called with one argument, the data value in a received ssh_cm message (see ssh_connection. The fun is to return either true to end the receiving operation (and have the so far collected data returned) or false to wait for more data from the server. Even if a fun is supplied, the function returns immediately if the server closes the channel).

rename(SSH, OldName, NewName)

-spec rename(SSH, OldName, NewName) -> Result
                when
                    SSH :: connection(),
                    OldName :: file:filename(),
                    NewName :: file:filename(),
                    Result :: ok | {error, Reason},
                    Reason :: term().

For information and other types, see ssh_sftp.

rename(SSH, Server, OldName, NewName)

-spec rename(SSH, Server, OldName, NewName) -> Result
                when
                    SSH :: connection(),
                    Server :: pid(),
                    OldName :: file:filename(),
                    NewName :: file:filename(),
                    Result :: ok | {error, Reason},
                    Reason :: term().

For information and other types, see ssh_sftp.

send(SSH, ChannelId, Data)

-spec send(SSH, ChannelId, Data) -> ok | {error, Reason}
              when
                  SSH :: connection(), ChannelId :: ssh_channel_id(), Data :: iodata(), Reason :: term().

Equivalent to send(SSH, ChannelId, 0, Data, DefaultTimeout).

send/4

-spec send(SSH, ChannelId, Data, Timeout) -> ok | {error, Reason}
              when
                  SSH :: connection(),
                  ChannelId :: ssh_channel_id(),
                  Data :: iodata(),
                  Timeout :: timeout(),
                  Reason :: term();
          (SSH, ChannelId, Type, Data) -> ok | {error, Reason}
              when
                  SSH :: connection(),
                  ChannelId :: ssh_channel_id(),
                  Type :: ssh_data_type_code(),
                  Data :: iodata(),
                  Reason :: term().

Sends data to server on specified session channel (see send/5).

Equivalent to send(SSH, ChannelId, 0, Data, Timeout) if called with Timeout being integer.

Equivalent to send(SSH, ChannelId, Type, Data, DefaultTimeout) if called with Type being integer.

send(SSH, ChannelId, Type, Data, Timeout)

-spec send(SSH, ChannelId, Type, Data, Timeout) -> ok | {error, Reason}
              when
                  SSH :: connection(),
                  ChannelId :: ssh_channel_id(),
                  Type :: ssh_data_type_code(),
                  Data :: iodata(),
                  Timeout :: timeout(),
                  Reason :: term().

Sends data to server on specified session channel.

send_and_receive(SSH, ChannelId, Data)

-spec send_and_receive(SSH, ChannelId, Data) ->
                          {ok, ReceivedData} | {timeout, ReceivedData} | {error, Reason}
                          when
                              SSH :: connection(),
                              ChannelId :: ssh_channel_id(),
                              Data :: iodata(),
                              ReceivedData :: string(),
                              Reason :: term().

Equivalent to send_and_receive(SSH, ChannelId, 0, Data, close, DefaultTimeout).

send_and_receive/4

-spec send_and_receive(SSH, ChannelId, Data, End) ->
                          {ok, ReceivedData} | {timeout, ReceivedData} | {error, Reason}
                          when
                              SSH :: connection(),
                              ChannelId :: ssh_channel_id(),
                              Data :: iodata(),
                              End :: close | timeout | fun((string()) -> boolean()),
                              ReceivedData :: string(),
                              Reason :: term();
                      (SSH, ChannelId, Data, Timeout) ->
                          {ok, ReceivedData} | {timeout, ReceivedData} | {error, Reason}
                          when
                              SSH :: connection(),
                              ChannelId :: ssh_channel_id(),
                              Data :: iodata(),
                              Timeout :: timeout(),
                              ReceivedData :: string(),
                              Reason :: term();
                      (SSH, ChannelId, Type, Data) ->
                          {ok, ReceivedData} | {timeout, ReceivedData} | {error, Reason}
                          when
                              SSH :: connection(),
                              ChannelId :: ssh_channel_id(),
                              Type :: ssh_data_type_code(),
                              Data :: iodata(),
                              ReceivedData :: string(),
                              Reason :: term().

Sends data to server on specified session channel and waits to receive the server response (see send_and_receive/6).

Equivalent to send_and_receive(SSH, ChannelId, 0, Data, End, DefaultTimeout) if called with End being function.

Equivalent to send_and_receive(SSH, ChannelId, 0, Data, close, Timeout) if called with Timeout being integer.

Equivalent to send_and_receive(SSH, ChannelId, Type, Data, close, DefaultTimeout) if called with Type being integer.

send_and_receive/5

-spec send_and_receive(SSH, ChannelId, Data, End, Timeout) ->
                          {ok, ReceivedData} | {timeout, Data} | {error, Reason}
                          when
                              SSH :: connection(),
                              ChannelId :: ssh_channel_id(),
                              Data :: iodata(),
                              End :: close | timeout | fun((string()) -> boolean()),
                              Timeout :: timeout(),
                              ReceivedData :: string(),
                              Reason :: term();
                      (SSH, ChannelId, Type, Data, Timeout) ->
                          {ok, ReceivedData} | {timeout, ReceivedData} | {error, Reason}
                          when
                              SSH :: connection(),
                              ChannelId :: ssh_channel_id(),
                              Type :: ssh_data_type_code(),
                              Data :: iodata(),
                              Timeout :: timeout(),
                              ReceivedData :: string(),
                              Reason :: term();
                      (SSH, ChannelId, Type, Data, End) ->
                          {ok, ReceivedData} | {timeout, ReceivedData} | {error, Reason}
                          when
                              SSH :: connection(),
                              ChannelId :: ssh_channel_id(),
                              Type :: ssh_data_type_code(),
                              Data :: iodata(),
                              End :: close | timeout | fun((string()) -> boolean()),
                              ReceivedData :: string(),
                              Reason :: term().

Sends data to server on specified session channel and waits to receive the server response (see send_and_receive/6).

Equivalent to send_and_receive(SSH, ChannelId, 0, Data, End, Timeout) if called with Timeout being integer.

Equivalent to send_and_receive(SSH, ChannelId, Type, Data, close, Timeout) if called with Type being integer.

Equivalent to send_and_receive(SSH, ChannelId, Type, Data, End, DefaultTimeout) if called with End being function.

send_and_receive(SSH, ChannelId, Type, Data, End, Timeout)

-spec send_and_receive(SSH, ChannelId, Type, Data, End, Timeout) ->
                          {ok, ReceivedData} | {timeout, ReceivedData} | {error, Reason}
                          when
                              SSH :: connection(),
                              ChannelId :: ssh_channel_id(),
                              Type :: ssh_data_type_code(),
                              Data :: iodata(),
                              End :: close | timeout | fun((string()) -> boolean()),
                              Timeout :: timeout(),
                              ReceivedData :: string(),
                              Reason :: term().

Sends data to server on specified session channel and waits to receive the server response.

For details on argument End, see ct_ssh:receive_response/4.

session_close(SSH, ChannelId)

-spec session_close(SSH, ChannelId) -> ok | {error, Reason}
                       when SSH :: connection(), ChannelId :: ssh_channel_id(), Reason :: term().

Closes an SSH session channel.

session_open(SSH)

-spec session_open(SSH) -> {ok, ChannelId} | {error, Reason}
                      when SSH :: connection(), ChannelId :: ssh_channel_id(), Reason :: term().

Equivalent to session_open(SSH, DefaultTimeout).

session_open(SSH, Timeout)

-spec session_open(SSH, Timeout) -> {ok, ChannelId} | {error, Reason}
                      when
                          SSH :: connection(),
                          Timeout :: timeout(),
                          ChannelId :: ssh_channel_id(),
                          Reason :: term().

Opens a channel for an SSH session.

sftp_connect(SSH)

-spec sftp_connect(SSH) -> {ok, Server} | {error, Reason}
                      when SSH :: connection(), Server :: pid(), Reason :: term().

Starts an SFTP session on an already existing SSH connection. Server identifies the new session and must be specified whenever SFTP requests are to be sent.

shell(SSH, ChannelId)

(since OTP 20.0)

-spec shell(SSH, ChannelId) -> Result
               when
                   SSH :: connection(),
                   ChannelId :: ssh:ssh_channel_id(),
                   Result :: ok | {error, term()}.

Equivalent to shell(SSH, ChannelId, DefaultTimeout).

shell(SSH, ChannelId, Timeout)

(since OTP 20.0)

-spec shell(SSH, ChannelId, Timeout) -> Result
               when
                   SSH :: connection(),
                   ChannelId :: ssh:ssh_channel_id(),
                   Timeout :: timeout(),
                   Result :: ok | {error, term()}.

Requests that the user's default shell (typically defined in /etc/passwd in Unix systems) is executed at the server end.

subsystem(SSH, ChannelId, Subsystem)

-spec subsystem(SSH, ChannelId, Subsystem) -> Status | {error, Reason}
                   when
                       SSH :: connection(),
                       ChannelId :: ssh_channel_id(),
                       Subsystem :: string(),
                       Status :: success | failure,
                       Reason :: term().

Equivalent to subsystem(SSH, Channel, Subsystem, DefaultTimeout).

subsystem(SSH, ChannelId, Subsystem, Timeout)

-spec subsystem(SSH, ChannelId, Subsystem, Timeout) -> Status | {error, Reason}
                   when
                       SSH :: connection(),
                       ChannelId :: ssh_channel_id(),
                       Subsystem :: string(),
                       Timeout :: timeout(),
                       Status :: success | failure,
                       Reason :: term().

Sends a request to execute a predefined subsystem.

write(SSH, Handle, Data)

-spec write(SSH, Handle, Data) -> Result
               when
                   SSH :: connection(),
                   Handle :: term(),
                   Data :: iodata(),
                   Result :: ok | {error, Reason},
                   Reason :: term().

For information and other types, see ssh_sftp.

write(SSH, Server, Handle, Data)

-spec write(SSH, Server, Handle, Data) -> Result
               when
                   SSH :: connection(),
                   Server :: pid(),
                   Handle :: term(),
                   Data :: iodata(),
                   Result :: ok | {error, Reason},
                   Reason :: term().

For information and other types, see ssh_sftp.

write_file(SSH, File, Iolist)

-spec write_file(SSH, File, Iolist) -> Result
                    when
                        SSH :: connection(),
                        File :: file:filename(),
                        Iolist :: iodata(),
                        Result :: ok | {error, Reason},
                        Reason :: term().

For information and other types, see ssh_sftp.

write_file(SSH, Server, File, Iolist)

-spec write_file(SSH, Server, File, Iolist) -> Result
                    when
                        SSH :: connection(),
                        Server :: pid(),
                        File :: file:filename(),
                        Iolist :: iodata(),
                        Result :: ok | {error, Reason},
                        Reason :: term().

For information and other types, see ssh_sftp.

write_file_info(SSH, Name, Info)

-spec write_file_info(SSH, Name, Info) -> Result
                         when
                             SSH :: connection(),
                             Name :: file:filename(),
                             Info :: file:file_info(),
                             Result :: ok | {error, Reason},
                             Reason :: term().

For information and other types, see ssh_sftp.

write_file_info(SSH, Server, Name, Info)

-spec write_file_info(SSH, Server, Name, Info) -> Result
                         when
                             SSH :: connection(),
                             Server :: pid(),
                             Name :: file:filename(),
                             Info :: file:file_info(),
                             Result :: ok | {error, Reason},
                             Reason :: term().

For information and other types, see ssh_sftp.

ct_suite behaviour

The following section describes the mandatory and optional test suite functions that Common Test calls during test execution. For more details, see section Writing Test Suites in the User's Guide.

Summary

Types

ct_config()

The configuration data that can be modified.

ct_group_def()

The test group definition, as returned by Module:groups/0.

ct_group_props()

ct_group_props_ref()

ct_group_ref()

ct_group_repeat_type()

ct_groupname()

The name of the test group.

ct_hooks()

ct_info()

The test suite information, as returned by Module:suite/0, Module:group/1 and Module:Testcase/0.

ct_info_required()

ct_info_required_subkeys()

ct_info_timetrap()

ct_info_timetrap_fun()

ct_status()

The status value for a nested subgroup.

ct_subgroups_def()

ct_test_def()

The test suite definition, as returned by Module:all/0.

ct_test_repeat()

ct_testcase_ref()

ct_testcase_repeat_prop()

ct_testname()

The name of the testcase function.

Callbacks

all()

Returns the list of all test cases and test case groups in the test suite module to be executed.

end_per_group(GroupName, Config)

This function is called after the execution of a test case group is finished. It is meant to be used for cleaning up after Module:init_per_group/2.

end_per_suite(Config)

This function is called as the last test case in the suite. It is meant to be used for cleaning up after Module:init_per_suite/1.

end_per_testcase(TestCase, Config)

This function is called after each test case, and can be used to clean up after Module:init_per_testcase/2 and the test case.

group(GroupName)

The test case group information function. It is supposed to return a list of tagged tuples that specify various properties related to the execution of a test case group (that is, its test cases and subgroups). Properties set by Module:group/1 override properties with the same key that have been set previously by Module:suite/0.

groups()

Defines test case groups. For details, see section Test Case Groups in the User's Guide.

init_per_group(GroupName, Config)

This configuration function is called before execution of a test case group. It typically contains initializations that are common for all test cases and subgroups in the group, and that must only be performed once.

init_per_suite(Config)

This configuration function is called as the first function in the suite. It typically contains initializations that are common for all test cases in the suite, and that must only be done once.

init_per_testcase(TestCase, Config)

This function is called before each test case.

suite()

The test suite information function. Returns a list of tagged tuples specifying various properties related to the execution of this test suite (common for all test cases in the suite).

'Testcase'()

The test case information function. It is supposed to return a list of tagged tuples that specify various properties related to the execution of this particular test case. Properties set by Module:Testcase/0 override properties set previously for the test case by Module:group/1 or Module:suite/0.

'Testcase'(Config)

The implementation of a test case. Call the functions to test and check the result. If something fails, ensure the function causes a runtime error or call ct:fail/1,2 (which also causes the test case process to terminate).

Types

ct_config()

-type ct_config() :: [{Key :: atom(), Value :: term()}].

The configuration data that can be modified.

ct_group_def()

-type ct_group_def() ::
          {ct_groupname(),
           ct_group_props(),
           [ct_testname() | ct_group_def() | {group, ct_groupname()} | ct_testcase_ref()]}.

The test group definition, as returned by Module:groups/0.

ct_group_props()

(not exported)

-type ct_group_props() ::
          [parallel | sequence | shuffle |
           {shuffle, Seed :: {integer(), integer(), integer()}} |
           {ct_group_repeat_type(), ct_test_repeat()}].

ct_group_props_ref()

(not exported)

-type ct_group_props_ref() :: ct_group_props() | default.

ct_group_ref()

(not exported)

-type ct_group_ref() ::
          {group, ct_groupname()} |
          {group, ct_groupname(), ct_group_props_ref()} |
          {group, ct_groupname(), ct_group_props_ref(), ct_subgroups_def()}.

ct_group_repeat_type()

(not exported)

-type ct_group_repeat_type() ::
          repeat | repeat_until_all_ok | repeat_until_all_fail | repeat_until_any_ok |
          repeat_until_any_fail.

ct_groupname()

-type ct_groupname() :: atom().

The name of the test group.

ct_hooks()

(not exported)

-type ct_hooks() ::
          [CTHModule ::
               atom() |
               {CTHModule :: atom(), CTHInitArgs :: term()} |
               {CTHModule :: atom(), CTHInitArgs :: term(), CTHPriority :: integer()}].

ct_info()

-type ct_info() ::
          {timetrap, ct_info_timetrap()} |
          {require, ct_info_required()} |
          {require, Name :: atom(), ct_info_required()} |
          {userdata, UserData :: term()} |
          {silent_connections, Conns :: [atom()]} |
          {stylesheet, CSSFile :: string()} |
          {ct_hooks, CTHs :: ct_hooks()}.

The test suite information, as returned by Module:suite/0, Module:group/1 and Module:Testcase/0.

ct_info_required()

(not exported)

-type ct_info_required() ::
          Key ::
              atom() |
              {Key :: atom(), SubKeys :: ct_info_required_subkeys()} |
              {Key :: atom(), SubKey :: atom()} |
              {Key :: atom(), SubKey :: atom(), SubKeys :: ct_info_required_subkeys()}.

ct_info_required_subkeys()

(not exported)

-type ct_info_required_subkeys() :: SubKey :: atom() | [SubKey :: atom()].

ct_info_timetrap()

(not exported)

-type ct_info_timetrap() ::
          timeout() |
          {seconds, integer()} |
          {minutes, integer()} |
          {hours, integer()} |
          {Mod :: atom(), Func :: atom(), Args :: list()} |
          ct_info_timetrap_fun().

ct_info_timetrap_fun()

(not exported)

-type ct_info_timetrap_fun() :: fun().

ct_status()

-type ct_status() :: ok | skipped | failed.

The status value for a nested subgroup.

ct_subgroups_def()

(not exported)

-type ct_subgroups_def() ::
          {ct_groupname(), ct_group_props_ref()} |
          {ct_groupname(), ct_group_props_ref(), ct_subgroups_def()}.

ct_test_def()

-type ct_test_def() :: ct_testname() | ct_group_ref() | ct_testcase_ref().

The test suite definition, as returned by Module:all/0.

ct_test_repeat()

(not exported)

-type ct_test_repeat() :: integer() | forever.

ct_testcase_ref()

(not exported)

-type ct_testcase_ref() :: {testcase, ct_testname(), ct_testcase_repeat_prop()}.

ct_testcase_repeat_prop()

(not exported)

-type ct_testcase_repeat_prop() ::
          [{repeat, ct_test_repeat()} |
           {repeat_until_ok, ct_test_repeat()} |
           {repeat_until_fail, ct_test_repeat()}].

ct_testname()

-type ct_testname() :: atom().

The name of the testcase function.

Callbacks

all()

-callback all() -> [TestDef :: ct_test_def()] | {skip, Reason :: term()}.

Returns the list of all test cases and test case groups in the test suite module to be executed.

This list also specifies the order the cases and groups are executed by Common Test. A test case is represented by an atom, the name of the test case function, or a testcase tuple indicating that the test case shall be repeated. A test case group is represented by a group tuple, where GroupName, an atom, is the name of the group (defined in Module:groups/0). Execution properties for groups can also be specified, both for a top-level group and for any of its subgroups. Group execution properties specified here override properties in the group definition (see Module:groups/0). (With value default, the group definition properties are used).

If {skip, Reason} is returned, all test cases in the module are skipped and Reason is printed on the HTML result page.

For details on groups, see section Test Case Groups in the User's Guide.

end_per_group(GroupName, Config)

(optional)

-callback end_per_group(GroupName :: ct_groupname(), Config :: ct_config()) ->
                           term() | {return_group_result, Status :: ct_status()}.

This function is called after the execution of a test case group is finished. It is meant to be used for cleaning up after Module:init_per_group/2.

A status value for a nested subgroup can be returned with {return_group_result, Status}. The status can be retrieved in Module:end_per_group/2 for the group on the level above. The status is also used by Common Test for deciding if execution of a group is to proceed if property sequence or repeat_until_* is set.

For details about test case groups, see section Test Case Groups in the User's Guide.

If this function is defined, then Module:init_per_group/2 must also be defined.

end_per_suite(Config)

(optional)

-callback end_per_suite(Config :: ct_config()) -> term() | {save_config, SaveConfig :: ct_config()}.

This function is called as the last test case in the suite. It is meant to be used for cleaning up after Module:init_per_suite/1.

For information on save_config, see section Saving Configuration Data in the User's Guide.

If this function is defined, then Module:init_per_suite/1 must also be defined.

end_per_testcase(TestCase, Config)

(optional)

-callback end_per_testcase(TestCase :: ct_testname(), Config :: ct_config()) ->
                              term() | {fail, Reason :: term()} | {save_config, SaveConfig :: ct_config()}.

This function is called after each test case, and can be used to clean up after Module:init_per_testcase/2 and the test case.

Any return value (besides {fail, Reason} and {save_config, SaveConfig}) is ignored. By returning {fail, Reason}, TestCase is marked as faulty (even though it was successful in the sense that it returned a value instead of terminating).

For information on save_config, see section Saving Configuration Data in the User's Guide.

If this function is defined, then Module:init_per_testcase/2 must also be defined.

group(GroupName)

(since OTP R15B) (optional)

-callback group(GroupName :: ct_groupname()) -> [Info :: ct_info()].

The test case group information function. It is supposed to return a list of tagged tuples that specify various properties related to the execution of a test case group (that is, its test cases and subgroups). Properties set by Module:group/1 override properties with the same key that have been set previously by Module:suite/0.

Tag timetrap sets the maximum time that each test case is allowed to execute (including Module:init_per_testcase/2 and Module:end_per_testcase/2). If the timetrap time is exceeded, the test case fails with reason timetrap_timeout. A TimeFunc function can be used to set a new timetrap by returning a TimeVal. It can also be used to trigger a timetrap time-out by, at some point, returning a value other than a TimeVal. For details, see section Timetrap Time-Outs in the User's Guide.

Tag require specifies configuration variables required by test cases (or configuration functions) in the suite. If the required configuration variables are not found in any of the configuration files, all test cases in this group are skipped. For details about the require functionality, see function ct:require/1,2.

With userdata, the user can specify any test case group related information that can be read by calling ct:userdata/2.

Tag ct_hooks specifies the Common Test Hooks to be run with this suite.

Other tuples than the ones defined are ignored.

For details about the test case group information function, see section Group Information Function in the User's Guide.

groups()

(optional)

-callback groups() -> [GroupDef :: ct_group_def()].

Defines test case groups. For details, see section Test Case Groups in the User's Guide.

init_per_group(GroupName, Config)

(optional)

-callback init_per_group(GroupName :: ct_groupname(), Config :: ct_config()) ->
                            NewConfig :: ct_config() | {skip, Reason :: term()}.

This configuration function is called before execution of a test case group. It typically contains initializations that are common for all test cases and subgroups in the group, and that must only be performed once.

GroupName is the name of the group, as specified in the group definition (see Module:groups/0). Parameter Config is the configuration data that can be modified. The return value of this function is given as Config to all test cases and subgroups in the group.

If {skip, Reason} is returned, all test cases in the group are skipped and Reason is printed in the overview log for the group.

For information about test case groups, see section Test Case Groups in the User's Guide.

If this function is defined, then Module:end_per_group/2 must also be defined.

init_per_suite(Config)

(optional)

-callback init_per_suite(Config :: ct_config()) ->
                            NewConfig ::
                                ct_config() |
                                {skip, Reason :: term()} |
                                {skip_and_save, Reason :: term(), SaveConfig :: ct_config()}.

This configuration function is called as the first function in the suite. It typically contains initializations that are common for all test cases in the suite, and that must only be done once.

Parameter Config is the configuration data that can be modified. Whatever is returned from this function is specified as Config to all configuration functions and test cases in the suite.

If {skip, Reason} is returned, all test cases in the suite are skipped and Reason is printed in the overview log for the suite.

For information on save_config and skip_and_save, see section Saving Configuration Data in the User's Guide.

If this function is defined, then Module:end_per_suite/1 must also be defined.

init_per_testcase(TestCase, Config)

(optional)

-callback init_per_testcase(TestCase :: ct_testname(), Config :: ct_config()) ->
                               NewConfig ::
                                   ct_config() | {fail, Reason :: term()} | {skip, Reason :: term()}.

This function is called before each test case.

Argument TestCase is the test case name, and Config (list of key-value tuples) is the configuration data that can be modified. The NewConfig list returned from this function is given as Config to the test case.

If {fail, Reason} is returned, the test case is marked as failed without being executed.

If {skip, Reason} is returned, the test case is skipped and Reason is printed in the overview log for the suite.

If this function is defined, then Module:end_per_testcase/2 must also be defined.

suite()

(optional)

-callback suite() -> [Info :: ct_info()].

The test suite information function. Returns a list of tagged tuples specifying various properties related to the execution of this test suite (common for all test cases in the suite).

Tag timetrap sets the maximum time that each test case is allowed to execute (including Module:init_per_testcase/2 and Module:end_per_testcase/2). If the timetrap time is exceeded, the test case fails with reason timetrap_timeout. A TimeFunc function can be used to set a new timetrap by returning a TimeVal. It can also be used to trigger a timetrap time-out by, at some point, returning a value other than a TimeVal. For details, see section Timetrap Time-Outs in the User's Guide.

Tag require specifies configuration variables required by test cases (or configuration functions) in the suite. If the required configuration variables are not found in any of the configuration files, all test cases are skipped. For details about the require functionality, see function ct:require/1,2.

With userdata, the user can specify any test suite-related information, which can be read by calling ct:userdata/2.

Tag ct_hooks specifies the Common Test Hooks to be run with this suite.

Other tuples than the ones defined are ignored.

For details about the test suite information function, see section Test Suite Information Function in the User's Guide.

'Testcase'()

(since OTP R14B) (optional)

-callback 'Testcase'() -> [ct_info()].

The test case information function. It is supposed to return a list of tagged tuples that specify various properties related to the execution of this particular test case. Properties set by Module:Testcase/0 override properties set previously for the test case by Module:group/1 or Module:suite/0.

Tag timetrap sets the maximum time that the test case is allowed to execute. If the timetrap time is exceeded, the test case fails with reason timetrap_timeout. Module:init_per_testcase/2 and Module:end_per_testcase/2 are included in the timetrap time. A TimeFunc function can be used to set a new timetrap by returning a TimeVal. It can also be used to trigger a timetrap time-out by, at some point, returning a value other than a TimeVal. For details, see section Timetrap Time-Outs in the User's Guide.

Tag require specifies configuration variables that are required by the test case (or init_per_testcase/2 or end_per_testcase/2). If the required configuration variables are not found in any of the configuration files, the test case is skipped. For details about the require functionality, see function ct:require/1,2.

If timetrap or require is not set, the default values specified by Module:suite/0 (or Module:group/1) are used.

With userdata, the user can specify any test case-related information that can be read by calling ct:userdata/3.

Other tuples than the ones defined are ignored.

For details about the test case information function, see section Test Case Information Function in the User's Guide.

'Testcase'(Config)

(since OTP R14B) (optional)

-callback 'Testcase'(Config) ->
                        term() |
                        {skip, Reason} |
                        {fail, Reason} |
                        {comment, Comment} |
                        {save_config, SaveConfig} |
                        {skip_and_save, Reason, SaveConfig}
                        when
                            Config :: ct_config(),
                            SaveConfig :: ct_config(),
                            Reason :: term(),
                            Comment :: string().

The implementation of a test case. Call the functions to test and check the result. If something fails, ensure the function causes a runtime error or call ct:fail/1,2 (which also causes the test case process to terminate).

Elements from the Config list can, for example, be read with proplists:get_value/2 in STDLIB.

Possible return values are:

{fail, Reason} - The test case is considered failed, and the Reason will be logged.

{skip, Reason} - The test case is considered skipped, and the Reason will be logged.

{comment, Comment} - The test case is considered successful, and the Comment will be logged.

{save_config, SaveConfig} - The test case is considered successful, and the SaveConfig will be stored in the Config (see section Saving Configuration Data in the User's Guide).

{skip_and_save, Reason, SaveConfig} - The test case is considered skipped, the Reason will be logged, and the SaveConfig will be stored in the Config (see section Saving Configuration Data in the User's Guide).

If the function returns any other term, the test case is considered successful.

If the test case function crashes, it is considered failed.

For details about test case implementation, see section Test Cases in the User's Guide.

ct_telnet

Common Test specific layer on top of Telnet client ct_telnet_client.erl.

Use this module to set up Telnet connections, send commands, and perform string matching on the result. For information about how to use ct_telnet and configure connections, specifically for UNIX hosts, see the unix_telnet manual page.

Default values defined in ct_telnet:

Connection timeout (time to wait for connection) = 10 seconds

Command timeout (time to wait for a command to return) = 10 seconds

Max number of reconnection attempts = 3

Reconnection interval (time to wait in between reconnection attempts) = 5 seconds

Keep alive (sends NOP to the server every 8 sec if connection is idle) = true

Polling limit (max number of times to poll to get a remaining string terminated) = 0

Polling interval (sleep time between polls) = 1 second

The TCP_NODELAY option for the telnet socket is disabled (set to false) per default

These parameters can be modified by the user with the following configuration term:

{telnet_settings, [{connect_timeout,Millisec},
                   {command_timeout,Millisec},
                   {reconnection_attempts,N},
                   {reconnection_interval,Millisec},
                   {keep_alive,Bool},
                   {poll_limit,N},
                   {poll_interval,Millisec},
                   {tcp_nodelay,Bool}]}.

Millisec = timeout(), N = integer()

Enter the telnet_settings term in a configuration file included in the test and ct_telnet retrieves the information automatically.

keep_alive can be specified per connection, if necessary. For details, see unix_telnet.

Logging

The default logging behavior of ct_telnet is to print information about performed operations, commands, and their corresponding results to the test case HTML log. The following is not printed to the HTML log: text strings sent from the Telnet server that are not explicitly received by a ct_telnet function, such as expect/3. However, ct_telnet can be configured to use a special purpose event handler, implemented in ct_conn_log_h, for logging all Telnet traffic. To use this handler, install a Common Test hook named cth_conn_log. Example (using the test suite information function):

suite() ->
    [{ct_hooks, [{cth_conn_log, [{conn_mod(),hook_options()}]}]}].

conn_mod() is the name of the Common Test module implementing the connection protocol, that is, ct_telnet.

The cth_conn_log hook performs unformatted logging of Telnet data to a separate text file. All Telnet communication is captured and printed, including any data sent from the server. The link to this text file is located at the top of the test case HTML log.

By default, data for all Telnet connections is logged in one common file (named default), which can get messy, for example, if multiple Telnet sessions are running in parallel. Therefore a separate log file can be created for each connection. To configure this, use hook option hosts and list the names of the servers/connections to be used in the suite. The connections must be named for this to work (see ct_telnet:open/1,2,3,4).

Hook option log_type can be used to change the cth_conn_log behavior. The default value of this option is raw, which results in the behavior described above. If the value is set to html, all Telnet communication is printed to the test case HTML log instead.

For raw logs, prefix option can be used for adjusting prefix data added to connection log. The default value of this option is disabled, which results with no prefix data. If the value is set to full prefix contains timestamp and additonal information. If the value is set to short prefix includes only human readable timestamp.

All cth_conn_log hook options described can also be specified in a configuration file with configuration variable ct_conn_log.

Example:

{ct_conn_log, [{ct_telnet,[{log_type,raw},
                           {hosts,[key_or_name()]}]}]}

Note

Hook options specified in a configuration file overwrite any hard-coded hook options in the test suite.

Logging Example:

The following ct_hooks statement causes printing of Telnet traffic to separate logs for the connections server1 and server2. Traffic for any other connections is logged in the default Telnet log.

suite() ->
    [{ct_hooks,
      [{cth_conn_log, [{ct_telnet,[{hosts,[server1,server2]}]}]}]}].

As previously explained, this specification can also be provided by an entry like the following in a configuration file:

{ct_conn_log, [{ct_telnet,[{hosts,[server1,server2]}]}]}.

In this case the ct_hooks statement in the test suite can look as follows:

suite() ->
    [{ct_hooks, [{cth_conn_log, []}]}].

See Also

unix_telnet

Summary

Types

connection()

Reference to opened Telnet connection associated to either a handle or target_name.

connection_type()

Telnet connection_type, valid values: 'telnet' | 'ts1' | 'ts2'.

handle()

Handle for a specific Telnet connection, see module ct.

newline_option()

See cmd/3 for explanation.

prompt_regexp()

Regular expression matching all possible prompts for a specific target type. regexp must not have any groups, that is, when matching, re:run/3 (in STDLIB) must return a list with one single element.

Functions

close(Connection)

Closes the Telnet connection and stops the process managing it.

cmd(Connection, Cmd)

Equivalent to cmd(Connection, Cmd, []).

cmd(Connection, Cmd, Opts)

Sends a command through Telnet and waits for prompt.

cmdf(Connection, CmdFormat, Args)

Equivalent to cmdf(Connection, CmdFormat, Args, []).

cmdf(Connection, CmdFormat, Args, Opts)

Sends a Telnet command and waits for prompt (uses a format string and a list of arguments to build the command).

expect(Connection, Patterns)

Equivalent to expect(Connection, Patterns, []).

expect(Connection, Patterns, Opts)

Gets data from Telnet and waits for the expected pattern.

get_data(Connection)

Gets all data received by the Telnet client since the last command was sent. Only newline-terminated strings are returned. If the last received string has not yet been terminated, the connection can be polled automatically until the string is complete.

open(Name)

Equivalent to open(Name, telnet).

open(Name, ConnType)

Opens a Telnet connection to the specified target host.

open(KeyOrName, ConnType, TargetMod)

Equivalent to open(KeyOrName, ConnType, TargetMod, KeyOrName).

open(KeyOrName, ConnType, TargetMod, Extra)

Opens a Telnet connection to the specified target host.

send(Connection, Cmd)

Equivalent to send(Connection, Cmd, []).

send(Connection, Cmd, Opts)

Sends a Telnet command and returns immediately.

sendf(Connection, CmdFormat, Args)

Equivalent to sendf(Connection, CmdFormat, Args, []).

sendf(Connection, CmdFormat, Args, Opts)

Sends a Telnet command and returns immediately (uses a format string and a list of arguments to build the command).

Types

connection()

-type connection() :: handle() | {ct:target_name(), connection_type()} | ct:target_name().

Reference to opened Telnet connection associated to either a handle or target_name.

connection_type()

-type connection_type() :: telnet | ts1 | ts2.

Telnet connection_type, valid values: 'telnet' | 'ts1' | 'ts2'.

handle()

-type handle() :: ct:handle().

Handle for a specific Telnet connection, see module ct.

newline_option()

(not exported)

-type newline_option() :: {newline, boolean() | string()}.

See cmd/3 for explanation.

prompt_regexp()

-type prompt_regexp() :: string().

Regular expression matching all possible prompts for a specific target type. regexp must not have any groups, that is, when matching, re:run/3 (in STDLIB) must return a list with one single element.

Functions

close(Connection)

-spec close(Connection) -> ok | {error, Reason}
               when Connection :: connection(), Reason :: already_closed | term().

Closes the Telnet connection and stops the process managing it.

A connection can be associated with a target name and/or a handle. If Connection has no associated target name, it can only be closed with the handle value (see ct_telnet:open/4).

cmd(Connection, Cmd)

-spec cmd(Connection, Cmd) -> {ok, Data} | {error, Reason}
             when Connection :: connection(), Cmd :: iodata(), Data :: string(), Reason :: term().

Equivalent to cmd(Connection, Cmd, []).

cmd(Connection, Cmd, Opts)

-spec cmd(Connection, Cmd, Opts) -> {ok, Data} | {error, Reason}
             when
                 Connection :: connection(),
                 Cmd :: iodata(),
                 Opts :: [{timeout, Timeout} | newline_option()] | Timeout,
                 Timeout :: integer(),
                 Data :: string(),
                 Reason :: term().

Sends a command through Telnet and waits for prompt.

By default, this function adds "\n" to the end of the specified command. If this is not desired, use option {newline,false}. This is necessary, for example, when sending Telnet command sequences prefixed with character Interpret As Command (IAC). Option {newline,string()} can also be used if a different line end than "\n" is required, for instance {newline,"\r\n"}, to add both carriage return and newline characters.

Option timeout specifies how long the client must wait for prompt. If the time expires, the function returns {error,timeout}. For information about the default value for the command timeout, see the list of default values in the beginning of this module.

cmdf(Connection, CmdFormat, Args)

-spec cmdf(Connection, CmdFormat, Args) -> {ok, Data} | {error, Reason}
              when
                  Connection :: connection(),
                  CmdFormat :: io:format(),
                  Args :: [term()],
                  Data :: string(),
                  Reason :: term().

Equivalent to cmdf(Connection, CmdFormat, Args, []).

cmdf(Connection, CmdFormat, Args, Opts)

-spec cmdf(Connection, CmdFormat, Args, Opts) -> {ok, Data} | {error, Reason}
              when
                  Connection :: connection(),
                  CmdFormat :: io:format(),
                  Args :: [term()],
                  Opts :: [{timeout, Timeout} | newline_option()] | Timeout,
                  Timeout :: integer(),
                  Data :: string(),
                  Reason :: term().

Sends a Telnet command and waits for prompt (uses a format string and a list of arguments to build the command).

For details, see ct_telnet:cmd/3.

expect(Connection, Patterns)

-spec expect(Connection, Patterns) ->
                {ok, Match} | {ok, Match, HaltReason} | {error, Reason} | no_return()
                when
                    Connection :: connection(),
                    Patterns :: Pattern | [Pattern],
                    Pattern :: PatternString | {Tag, PatternString},
                    Tag :: term(),
                    PatternString :: unicode:charlist(),
                    Match :: MatchResult | [MatchResult],
                    MatchResult ::
                        [CaptureData | {Tag, CaptureData}] | [[CaptureData | {Tag, CaptureData}]],
                    CaptureData ::
                        string() | {error, string(), binary()} | {incomplete, string(), binary()},
                    HaltReason :: MatchResult,
                    Reason :: term().

Equivalent to expect(Connection, Patterns, []).

expect(Connection, Patterns, Opts)

-spec expect(Connection, Patterns, Opts) ->
                {ok, Match} | {ok, Match, HaltReason} | {error, Reason} | no_return()
                when
                    Connection :: connection(),
                    Patterns :: Pattern | [Pattern],
                    Pattern :: PatternString | {Tag, PatternString},
                    Tag :: term(),
                    PatternString :: unicode:charlist(),
                    Opts :: [Option],
                    Option ::
                        {idle_timeout, non_neg_integer()} |
                        {total_timeout, non_neg_integer()} |
                        ignore_prompt | no_prompt_check | wait_for_prompt | repeat |
                        {repeat, non_neg_integer()} |
                        sequence |
                        {halt, Patterns},
                    Match :: MatchResult | [MatchResult],
                    MatchResult ::
                        [CaptureData | {Tag, CaptureData}] | [[CaptureData | {Tag, CaptureData}]],
                    CaptureData ::
                        string() | {error, string(), binary()} | {incomplete, string(), binary()},
                    HaltReason :: MatchResult,
                    Reason :: term().

Gets data from Telnet and waits for the expected pattern.

Pattern can be a POSIX regular expression. The function returns when a pattern is successfully matched (at least one, in the case of multiple patterns).

RxMatch is a list of matched strings. It looks as follows [FullMatch, SubMatch1, SubMatch2, ...], where FullMatch is the string matched by the whole regular expression, and SubMatchN is the string that matched subexpression number N. Subexpressions are denoted with '(' ')' in the regular expression.

If a Tag is specified, the returned Match also includes the matched Tag. Otherwise, only RxMatch is returned.

Options:

idle_timeout - Indicates that the function must return if the Telnet client is idle (that is, if no data is received) for more than IdleTimeout milliseconds. Default time-out is 10 seconds.

total_timeout - Sets a time limit for the complete expect operation. After TotalTimeout milliseconds, {error,timeout} is returned. Default is infinity (that is, no time limit).

ignore_prompt | no_prompt_check - >The function returns when a prompt is received, even if no pattern has yet been matched, and {error,{prompt,Prompt}} is returned. However, this behavior can be modified with option ignore_prompt or option no_prompt_check, which tells expect to return only when a match is found or after a time-out.

ignore_prompt - ct_telnet ignores any prompt found. This option is useful if data sent by the server can include a pattern matching prompt regexp (as returned by TargedMod:get_prompt_regexp/0), but is not to not cause the function to return.

no_prompt_check - ct_telnet does not search for a prompt at all. This is useful if, for example, Pattern itself matches the prompt.

wait_for_prompt - Forces ct_telnet to wait until the prompt string is received before returning (even if a pattern has already been matched). This is equal to calling expect(Conn, Patterns++[{prompt,Prompt}], [sequence|Opts]). Notice that option idle_timeout and total_timeout can abort the operation of waiting for prompt.

repeat | repeat, N - The pattern(s) must be matched multiple times. If N is specified, the pattern(s) are matched N times, and the function returns HaltReason = done. This option can be interrupted by one or more HaltPatterns. MatchList is always returned, that is, a list of Match instead of only one Match. Also HaltReason is returned.

sequence - All patterns must be matched in a sequence. A match is not concluded until all patterns are matched. This option can be interrupted by one or more HaltPatterns. MatchList is always returned, that is, a list of Match instead of only one Match. Also HaltReason is returned.

Example 1:

expect(Connection,[{abc,"ABC"},{xyz,"XYZ"}],[sequence,{halt,[{nnn,"NNN"}]}])

First this tries to match "ABC", and then "XYZ", but if "NNN" appears, the function returns {error,{nnn,["NNN"]}}. If both "ABC" and "XYZ" are matched, the function returns {ok,[AbcMatch,XyzMatch]}.

Example 2:

expect(Connection,[{abc,"ABC"},{xyz,"XYZ"}],[{repeat,2},{halt,[{nnn,"NNN"}]}])

This tries to match "ABC" or "XYZ" twice. If "NNN" appears, the function returns HaltReason = {nnn,["NNN"]}.

Options repeat and sequence can be combined to match a sequence multiple times.

get_data(Connection)

-spec get_data(Connection) -> {ok, Data} | {error, Reason}
                  when Connection :: connection(), Data :: string(), Reason :: term().

Gets all data received by the Telnet client since the last command was sent. Only newline-terminated strings are returned. If the last received string has not yet been terminated, the connection can be polled automatically until the string is complete.

The polling feature is controlled by the configuration values poll_limit and poll_interval and is by default disabled. This means that the function immediately returns all complete strings received and saves a remaining non-terminated string for a later get_data call.

open(Name)

-spec open(Name) -> {ok, Handle} | {error, Reason}
              when Name :: atom(), Handle :: handle(), Reason :: term().

Equivalent to open(Name, telnet).

open(Name, ConnType)

-spec open(Name, ConnType) -> {ok, Handle} | {error, Reason}
              when Name :: atom(), ConnType :: connection_type(), Handle :: handle(), Reason :: term().

Opens a Telnet connection to the specified target host.

open(KeyOrName, ConnType, TargetMod)

-spec open(KeyOrName, ConnType, TargetMod) -> {ok, Handle} | {error, Reason}
              when
                  KeyOrName :: ct:key_or_name(),
                  ConnType :: connection_type(),
                  TargetMod :: module(),
                  Handle :: handle(),
                  Reason :: term().

Equivalent to open(KeyOrName, ConnType, TargetMod, KeyOrName).

open(KeyOrName, ConnType, TargetMod, Extra)

-spec open(KeyOrName, ConnType, TargetMod, Extra) -> {ok, Handle} | {error, Reason}
              when
                  KeyOrName :: ct:key_or_name(),
                  ConnType :: connection_type(),
                  TargetMod :: module(),
                  Extra :: term(),
                  Handle :: handle(),
                  Reason :: term().

Opens a Telnet connection to the specified target host.

The target data must exist in a configuration file. The connection can be associated with Name and/or the returned Handle. To allocate a name for the target, use one of the following alternatives:

ct:require/2 in a test case

A require statement in the suite information function (suite/0)

A require statement in a test case information function

If you want the connection to be associated with Handle only (if you, for example, need to open multiple connections to a host), use Key, the configuration variable name, to specify the target. Notice that a connection without an associated target name can only be closed with the Handle value.

TargetMod is a module that exports the functions connect(Ip, Port, KeepAlive, Extra) and get_prompt_regexp() for the specified TargetType (for example, unix_telnet).

See also ct:require/2.

send(Connection, Cmd)

-spec send(Connection, Cmd) -> ok | {error, Reason}
              when Connection :: connection(), Cmd :: iodata(), Reason :: term().

Equivalent to send(Connection, Cmd, []).

send(Connection, Cmd, Opts)

(since OTP 17.4)

-spec send(Connection, Cmd, Opts) -> ok | {error, Reason}
              when
                  Connection :: connection(),
                  Cmd :: iodata(),
                  Opts :: [newline_option()],
                  Reason :: term().

Sends a Telnet command and returns immediately.

By default, this function adds "\n" to the end of the specified command. If this is not desired, option {newline,false} can be used. This is necessary, for example, when sending Telnet command sequences prefixed with character Interpret As Command (IAC). Option {newline,string()} can also be used if a different line end than "\n" is required, for instance {newline,"\r\n"}, to add both carriage return and newline characters.

The resulting output from the command can be read with ct_telnet:get_data/2 or ct_telnet:expect/2,3.

sendf(Connection, CmdFormat, Args)

-spec sendf(Connection, CmdFormat, Args) -> ok | {error, Reason}
               when
                   Connection :: connection(),
                   CmdFormat :: io:format(),
                   Args :: [term()],
                   Reason :: term().

Equivalent to sendf(Connection, CmdFormat, Args, []).

sendf(Connection, CmdFormat, Args, Opts)

(since OTP 17.4)

-spec sendf(Connection, CmdFormat, Args, Opts) -> ok | {error, Reason}
               when
                   Connection :: connection(),
                   CmdFormat :: io:format(),
                   Args :: [term()],
                   Opts :: [newline_option()],
                   Reason :: term().

Sends a Telnet command and returns immediately (uses a format string and a list of arguments to build the command).

For details, see ct_telnet:send/3.

ct_testspec

Parsing of test specifications for Common Test.

This module exports help functions for parsing of test specifications.

Summary

Functions

get_tests(Specs)

Parse the given test specification files and return the tests to run and skip.

Functions

get_tests(Specs)

(since OTP 19.3)

-spec get_tests(Specs) -> {ok, [{Specs, Tests}]} | {error, Reason}
                   when
                       Specs :: [string()] | [[string()]],
                       Tests :: {Node, Run, Skip},
                       Node :: atom(),
                       Run :: {Dir, Suites, Cases},
                       Skip :: {Dir, Suites, Comment} | {Dir, Suites, Cases, Comment},
                       Dir :: string(),
                       Suites :: atom | [atom()] | all,
                       Cases :: atom | [atom()] | all,
                       Comment :: string(),
                       Reason :: term().

Parse the given test specification files and return the tests to run and skip.

If SpecsIn=[Spec1,Spec2,...], separate tests will be created per specification. If SpecsIn=[[Spec1,Spec2,...]], all specifications will be merge into one test.

For each test, a {Specs,Tests} element is returned, where Specs is a list of all included test specifications, and Tests specifies actual tests to run/skip per node.

unix_telnet

Callback module for ct_telnet, for connecting to a Telnet server on a UNIX host.

It requires the following entry in the configuration file:

{unix,[{telnet,HostNameOrIpAddress},
       {port,PortNum},                 % optional
       {username,UserName},
       {password,Password},
       {keep_alive,Bool}]}.            % optional

To communicate through Telnet to the host specified by HostNameOrIpAddress, use the interface functions in ct_telnet, for example, open(Name) and cmd(Name,Cmd).

Name is the name you allocated to the Unix host in your require statement, for example:

suite() -> [{require,Name,{unix,[telnet]}}].

or

ct:require(Name,{unix,[telnet]}).

The "keep alive" activity (that is, that Common Test sends NOP to the server every 10 seconds if the connection is idle) can be enabled or disabled for one particular connection as described here. It can be disabled for all connections using telnet_settings (see ct_telnet).

The {port,PortNum} tuple is optional and if omitted, default Telnet port 23 is used. Also the keep_alive tuple is optional, and the value default to true (enabled).

See Also

ct, ct_telnet

Summary

Functions

connect(ConnName, Ip, Port, Timeout, KeepAlive, TCPNoDelay, Extra)

Callback for ct_telnet.erl.

get_prompt_regexp()

Callback for ct_telnet.erl.

Functions

connect(ConnName, Ip, Port, Timeout, KeepAlive, TCPNoDelay, Extra)

(since OTP 18.3.3)

-spec connect(ConnName, Ip, Port, Timeout, KeepAlive, TCPNoDelay, Extra) ->
                 {ok, Handle} | {error, Reason}
                 when
                     ConnName :: ct:target_name(),
                     Ip :: inet:socket_address() | inet:hostname(),
                     Port :: inet:port_number(),
                     Timeout :: timeout(),
                     KeepAlive :: boolean(),
                     TCPNoDelay :: boolean(),
                     Extra :: {Username, Password} | KeyOrName,
                     Username :: iodata(),
                     Password :: iodata(),
                     KeyOrName :: ct:key_or_name(),
                     Handle :: ct_telnet:handle(),
                     Reason :: term().

Callback for ct_telnet.erl.

Setup Telnet connection to a Unix host.

get_prompt_regexp()

-spec get_prompt_regexp() -> Pattern when Pattern :: ct_telnet:prompt_regexp().

Callback for ct_telnet.erl.

Returns a suitable regexp string matching common prompts for users on Unix hosts.