IOError: [Errno 2] Нет такого файла или каталога - в Linux, используя абсолютный путь - PullRequest
0 голосов
/ 04 февраля 2019

Я изо всех сил пытаюсь найти решение для этого.Я использую абсолютный путь, который определенно существует в файловой системе.Когда один и тот же точный путь используется в том же сценарии с

if host.file(logPath).exists:
    print("Exists: " + logPath)

, я получаю

Exists: /var/opt/jws/jws3.0/v7/testinfra_node1/logs/catalina.out

Но при попытке:

with open(logPath, "rt") as log:

я получаю:

>               with open(logPath, "rt") as log:
E               IOError: [Errno 2] No such file or directory: '/var/opt/jws/jws3.0/v7/testinfra_node1/logs/catalina.out'

Вот весь код (это скрипт testinfra для тестирования установки JWT):

import pytest
import testinfra
import time
import os

@pytest.mark.parametrize("jws_version", [("3.0")])

def test_server_recycle(host, jws_version):
    instances = host.check_output("cat /var/opt/jws/jws" + jws_version + "/init/init_instances | grep -oP '(\/.*?\/)((?:[^\/]|\\\\/)+?)(?:(?<!\\\\)\s|$)'")
last = ""
for last in iter(instances.splitlines()):
    pass
last = last.strip().encode('ascii','ignore')
print(last)

instanceName = ""
for instanceName in iter(last.split("/")):
    pass
print(instanceName)

binPath = last + "/bin/"
logDir = last + "/logs/"
logPath = os.path.join(logDir, "catalina.out")
print(logPath)

runningAt0 = isInstanceRunning(host, instanceName)
if host.file(logPath).exists:
    print("Exists: " + logPath)

if (runningAt0):
    with host.sudo():
        host.run(os.path.join(binPath, "shutdown.sh"))    
        with open(logPath, "rt") as log:
            result = waitForEntry(log, "INFO  org.apache.catalina.core.StandardService- Stopping service Catalina","ERROR")
        assert not result.eq("ERROR")
        assert not isInstanceRunning(host, instanceName)
        host.run(os.path.join(binPath, "/bin/startup.sh"))
        with open(logPath, "rt") as log:
            result = waitForEntry(log, "INFO  org.apache.catalina.startup.Catalina- Server startup in","ERROR")
        assert not result.eq("ERROR")
        assert isInstanceRunning(host, instanceName)
else:
    with host.sudo():
        host.run(os.path.join(binPath, "startup.sh"))
        with open(logPath, "rt") as log:
            result = waitForEntry(log, "INFO  org.apache.catalina.core.StandardService- Stopping service Catalina","ERROR")
        assert not result.eq("ERROR")
        assert isInstanceRunning(host, instanceName)
        host.run(os.path.join(binPath, "shutdown.sh"))
        with open(logPath, "rt") as log:
            result = waitForEntry(log, "INFO  org.apache.catalina.startup.Catalina- Server startup in","ERROR")
        assert not result.eq("ERROR")
        assert not isInstanceRunning(host, instanceName)

def isInstanceRunning(host, instanceName):
    processes = host.check_output("ps auwwx | grep catalina.startup.Bootstrap")
    if  "-Dtomcat.inst.name=" + instanceName in processes:
        return True
    else:
        return False

def waitForEntry(file, entry1, entry2):
    while 1:
        file.seek(0,2)
        line = file.readline()
        if entry1 in line:
            return entry1
        else:
            if entry2 in line:
                return entry2
            else:
                time.sleep(0.1)

Вместо

host.file(logPath).exists

Я также пытался

print(host.check_output("cat " + logPath))

и он хорошо печатает содержимое файла.

Есть идеи, как к этому подойти?Заранее большое спасибо!

Редактировать: Вот как я выполняю скрипт:

py.test -v --host = user @ host tomcat_test_recycle.py --sudo

1 Ответ

0 голосов
/ 05 февраля 2019

Пакет testinfra, по-видимому, интегрирует тестирование состояния удаленных серверов в pytest.Таким образом,

host.file(logPath).exists

и

host.check_output("cat " + logPath)

проверяют существование и содержимое на удаленном сервере, тогда как

open(logPath, "rb") 

действуетна локальной машине.Файл не на локальной машине, он на host.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...