Completed
Push — add_bdd ( a2de90...b6b949 )
by Anatoliy
05:17
created

Main::accessForCreateRewrite()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 1
1
<?php
2
declare(strict_types=1);
3
4
use Behat\Behat\Context\Context;
5
use Behat\Gherkin\Node\PyStringNode;
6
use Behat\Gherkin\Node\TableNode;
7
use DanchukAS\Mock\PidFileTestCase;
8
use PHPUnit\Framework\Assert;
9
10
/**
11
 * Defines application Behat from the specific context.
12
 */
13
class Main implements Context
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
14
{
15
    private $varList = [];
16
17
    private $mainFile;
18
    private $mainCommand;
19
20
    private $attempts = [];
21
22
    private $pathAutoload = __DIR__ . '/../../../../vendor/autoload.php';
23
24
    /**
25
     * @Given access for create\/rewrite :pid_file
26
     * @param string $pid_file
27
     */
28
    public function accessForCreateRewrite(string $pid_file)
29
    {
30
        $filename = PidFileTestCase::generateTempFile();
31
32
        Assert::assertFileIsWritable($filename);
33
34
        $this->varList[$pid_file] = $filename;
35
    }
36
37
    /**
38
     * @Given runned :file_link which contains:
39
     * @param $file_link
40
     * @param PyStringNode $command
41
     */
42
    public function with($file_link, PyStringNode $command)
43
    {
44
        $filename = PidFileTestCase::generateTempFile();
45
        $do_seconds = 3;
46
47
        foreach ($this->varList as $var_name => $var_value) {
48
            if (is_array($var_value)) {
49
                continue;
50
            }
51
52
            if (is_string($var_value)) {
53
                $var_value = '"' . $var_value . '"';
54
            }
55
56
            $command = str_replace($var_name, $var_value, $command);
57
        }
58
59
60
        $file_content = <<<CONTENT
61
<?php 
62
    require "$this->pathAutoload";
63
    $command
64
    sleep($do_seconds);
65
CONTENT;
66
67
        file_put_contents($filename, $file_content);
68
69
        $this->mainFile = $filename;
70
        $this->mainCommand = $command;
71
72
        $this->varList[$file_link] = [
73
            'filename' => $filename
74
            , 'time' => $do_seconds
75
        ];
76
77
        static $descriptor_spec = [
78
            0 => ['pipe', 'r'],
79
            1 => ['pipe', 'w'],
80
            2 => ['pipe', 'w'],
81
            3 => ['pipe', 'w'] // for return result code
82
        ];
83
        $shell_command = "php -f {$filename}; echo $? >&3";
84
        $process_res = proc_open($shell_command, $descriptor_spec, $pipes, null, []);
85
        /** @var array $proc_details */
86
        $proc_details = proc_get_status($process_res);
87
88
        $this->varList[$file_link] = [
89
            'filename' => $filename
90
            , 'time' => $do_seconds
91
            , 'pid' => $proc_details['pid']
92
            , 'resource' => $process_res
93
            , 'pipes' => $pipes
94
        ];
95
96
    }
0 ignored issues
show
Coding Style introduced by
Function closing brace must go on the next line following the body; found 1 blank lines before brace
Loading history...
97
98
    /**
99
     * @When try run <some-php-script> <any> times during running already runned :file_link
100
     */
101
    public function tryRunSomePhpScriptAnyTimesDuringRunningAlreadyRunned($file_link, TableNode $table)
102
    {
103
        $this->attempts = [];
104
105
        foreach ($table as $example) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
106
107
            while ($example['any']-- > 0) {
108
                $result_code = $this->run_php_file($example['some-php-script']);
109
                $this->attempts[$example['some-php-script']] = $result_code;
110
            }
111
112
            if (// Посилає сигнал процесу щоб дізнатись чи він існує.
113
                // Якщо true - точно існує.
114
                // якщо false - процес може і бути, але запущений під іншим користувачем або інші ситуації.
115
                false === posix_kill($this->varList[$file_link]['pid'], 0)
116
                // 3 = No such process (тестувалось в Ubuntu 14, FreeBSD 9. В інших ОС можуть відрізнятись)
117
                // Якщо процеса точно в даний момент нема такого.
118
                // Для визова цієї функції необхідний попередній визов posix_kill.
119
                && posix_get_last_error() === 3
120
            ) {
121
                Assert::fail();
122
            }
123
        }
124
125
    }
0 ignored issues
show
Coding Style introduced by
Function closing brace must go on the next line following the body; found 1 blank lines before brace
Loading history...
126
127
    private function run_php_file($php_file)
0 ignored issues
show
Coding Style introduced by
Method name "Main::run_php_file" is not in camel caps format
Loading history...
128
    {
129
        if ('<similar-php-script>' === $php_file
130
            && !isset($this->varList[$php_file])
131
        ) {
132
            $filename = PidFileTestCase::generateTempFile();
133
            copy($this->mainFile, $filename);
134
            $this->varList[$php_file]['filename'] = $filename;
135
        }
136
137
        $file_name = $this->varList[$php_file]['filename'];
138
139
        system("php -f {$file_name} 1>/dev/null 2>/dev/null", $result_code);
140
141
        return $result_code;
142
    }
143
144
    /**
145
     * @Then all attempts are failed
146
     */
147
    public function allAttemptsAreFailed()
148
    {
149
        $success_run_code = 0;
150
151
        foreach ($this->attempts as $php_script => $result_code) {
152
            Assert::assertNotEquals($success_run_code, $result_code);
153
        }
154
    }
155
156
157
    /**
158
     * @Then given runned :php_script work regardless of subsequent attempts
159
     */
160
    public function givenRunnedWorkRegardlessOfSubsequentAttempts($php_script)
161
    {
162
163
        $handle_exit_code = $this->varList[$php_script]['pipes'][3];
164
165
        $exit_code = !feof($handle_exit_code)
166
            ? rtrim(fgets($handle_exit_code, 5), "\n")
167
            : null;
168
169
        foreach ($this->varList[$php_script]['pipes'] as $pipe) {
170
            fclose($pipe);
171
        }
172
173
        proc_close($this->varList[$php_script]['resource']);
174
175
        $success_exit_code = 0;
176
        Assert::assertEquals($success_exit_code, $exit_code);
177
    }
178
179
180
}
181