1. Perl
  2. Module
  3. here

IO::ScalarArray - Active in standard input testing

This time, I will explain the automatic test of standard input using "IO::ScalarArray".

1. How to feed data to standard input

The standard input STDIN is a handle for input, and data cannot be written to it from within the program.

It is not possible to input data to the standard input, but it is possible to perform a simulated test. Read lines from standard input using a mechanism called tie

<STDIN>

Can be linked to the description of reading data from a variable. (I won't explain in detail here, but kits's tie replaces STDIN article explains how to do this. It has been.)

2. Standard input test using IO::ScalarArray

IO::ScalarArray is a module that uses the tie mechanism to enable descriptions that flow data into standard input. Use it as follows.

First, create an array of the data you want to flow into the standard input. Since the standard input has one line break, add a line break at the end of the data.

Pass it to new in IO::ScalarArray to create the object. Then use a typeglob to make STDIN an alias for $stdin.

use IO::ScalarArray;
{
  my @inputs = ("1\n", "2\n", "3\n");
  my $stdin = IO::ScalarArray->new(\@inputs);
  local * STDIN = * $stdin;
  # Exam description
}

(Reference) local

3 Standard input automatic test example

This is a test of a program that asks questions interactively. The question function is a function that asks if you are a man.

use Test::More tests => 1;
use strict;
use warnings;

use IO::ScalarArray;

{
  my @answers = ("y\n");
  my $stdin = IO::ScalarArray->new(\@answers);
  
  local * STDIN = * $stdin;
  
  my $is_man = question ();
  ok ($is_man, 'He is man');
}

# Function to ask if you are male
sub question {
  print "Are you man?\n";
  my $answer = <STDIN>;
  
  chomp $answer;
  my $is_man;
  if ($answer eq 'y') {$is_man = 1}
  else {$is_man = 0}
  
  return $is_man;
}

How to use scalar input/output

This is an example that uses Perl's scalar input/output function.

use Test::More tests => 1;
use strict;
use warnings;

{
  my $inputs = << "EOS";
y\n
n\n
EOS

  # How to use scalar input/output
  open my $stdin, "<", \$inputs;
  
  local * STDIN = * $stdin;
  
  my $is_man = question ();
  ok ($is_man, 'He is man');
  
  $is_man = question ();
  ok (!$Is_man, 'He is not man');
}

# Function to ask if you are male
sub question {
  print "Are you man?\n";
  my $answer = <STDIN>;
  
  chomp $answer;
  my $is_man;
  if ($answer eq 'y') {$is_man = 1}
  else {$is_man = 0}

  return $is_man;
}

Related Informatrion