Browse Source

test: scrippy_core complete test

test: scrippy_core complete test

Co-authored-by: mco-system <michael.costa@mcos.nc>
Reviewed-on: https://git.mcos.nc/scrippy/scrippy-core/pulls/5
Co-Authored-By: Michaël Costa <michael.costa@mcos.nc>
Co-Committed-By: Michaël Costa <michael.costa@mcos.nc>
pull/6/head
Michaël Costa 5 months ago
parent
commit
7a4912b9de
8 changed files with 372 additions and 23 deletions
  1. +19
    -8
      .drone.yml
  2. +1
    -1
      README.md
  3. +38
    -0
      tests/scrippy/git/ssh/scrippy.rsa
  4. +9
    -0
      tests/scrippy/sql/feed_db.sql
  5. +38
    -0
      tests/scrippy/ssh/scrippy.rsa
  6. +6
    -3
      tests/test_scrippy_core.conf
  7. +253
    -11
      tests/test_scrippy_core.py
  8. +8
    -0
      tests/test_scrippy_core.txt.j2

+ 19
- 8
.drone.yml View File

@ -12,20 +12,30 @@ steps:
from_secret: pip_user
pip_password:
from_secret: pip_password
db_connexion_string: postgres://postgres:postgres@scrippy_db:5432/scrippy
commands:
- sleep 30
- apt-get update
- apt-get install postgresql-client -y
- psql -Atx $${db_connexion_string} -f ./tests/scrippy/sql/feed_db.sql
- mkdir /etc/scrippy
- python3 -m pip install pip --upgrade
- python3 -m pip install .[dev]
- pip install -i https://$${pip_user}:$${pip_password}@pip.mcos.nc/simple/ --upgrade scrippy-template scrippy-remote scrippy-db scrippy-git scrippy-api scrippy-mail
- cp tests/scrippy/scrippy.yml /etc/scrippy/
- python3 tests/scrippy/setup.py
- chmod 700 ./tests/scrippy/git/ssh/
- chmod 600 ./tests/scrippy/git/ssh/scrippy.rsa
- chmod 700 ./tests/scrippy/ssh/
- chmod 600 ./tests/scrippy/ssh/scrippy.rsa
- cp tests/test_scrippy_core.conf /etc/scrippy/conf/
# - python3 "$(pwd)"/tests/test_scrippy_core.py
# On teste le nombre de lignes dans le dernier log
# Le nombre de lignes à retrouver doit être adapté à chaque modification du script du test
# - test $(python3 "$(pwd)"/tests/test_scrippy_core.py --log | grep -cE "\[test_scrippy_core_[0-9]+\.[0-9]+_[0-9]+\]") -eq 3
- cp tests/test_scrippy_core.txt.j2 /var/lib/scrippy/templates/
- python3 "$(pwd)"/tests/test_scrippy_core.py --remote_path /home/scrippy
--remote_filename message.txt
--local_path /var/tmp/scrippy/
--mail_recipient harry.fink@flying.circus
# On teste le nombre d'exécutions enregistrées dans l'historique
# - test $(python3 "$(pwd)"/tests/test_scrippy_core.py --hist | grep -cE "[0-9]+\.[0-9]+_[0-9]+") -eq 1
- test $(python3 "$(pwd)"/tests/test_scrippy_core.py --hist | grep -cE "[0-9]+\.[0-9]+_[0-9]+") -eq 1
when:
event:
exclude:
@ -91,8 +101,9 @@ services:
image: gitolite:latest
ports:
- 2201
- name: postgres
image: postgres:11.1-alpine
- name: scrippy_db
image: scrippy_db
pull: never
ports:
- 5432
environment:
@ -111,6 +122,6 @@ services:
- 2200
---
kind: signature
hmac: f06ba2d572caf27394fc8d0c45481d20668c6640fad3bdd6bb50ed4ba0438954
hmac: 850268c2f01840c36cf494869648915c30042f06694a35a152d93f30d6f3ee51
...

+ 1
- 1
README.md View File

@ -767,7 +767,7 @@ Dans l'exemple précédent la variable `workspace_path` contiendra le chemin ver
**Ex**:
```bash
/opt/expl/tmp/exp_transfert_ftp_1574391960.6696503_102257
/var/tmp/scrippy/exp_transfert_ftp_1574391960.6696503_102257
```
Cet espace de travail temporaire, qui sera *automatiquement détruit avec son contenu à la fin du script*, est un répertoire qui pourra être utilisé pour y créer des fichiers.


+ 38
- 0
tests/scrippy/git/ssh/scrippy.rsa View File

@ -0,0 +1,38 @@
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABlwAAAAdzc2gtcn
NhAAAAAwEAAQAAAYEAuxla+dRAYyJXjIBBmpt92FNAPWJrKZHKiaS6IMtFeP7qKjJGZ7jJ
UYodT1Ns+jTBkvyWZ2TQvIshJwCInmVft/QuVujer4hh8V7N+mNniRCH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
XMFvxNEl4BaLzc/QbCobUbs/JvfVwTCUjopS7sgGXMdkcPhPsjzCPzq4N3lPgbBSwAFlTO
9hGPdDFAnhP8BgA2ftw/zNIzAljxkDjbbKG2/81nGGnYElaCdYVU7xKBkch3dAt8o/V/8X
aTCocaMU7LQE8AAAAbZG91Z0BjeWJlcmxhYi5yZWRhdG9taWsub3Jn
-----END OPENSSH PRIVATE KEY-----

+ 9
- 0
tests/scrippy/sql/feed_db.sql View File

@ -0,0 +1,9 @@
DROP TABLE IF EXISTS users;
CREATE TABLE users(
id SERIAL PRIMARY KEY NOT NULL,
name TEXT NOT NULL,
givenname TEXT NOT NULL,
password TEXT NOT NULL
);
INSERT INTO users values (0, 'FINK', 'Harry', 'D34D P4RR0T');

+ 38
- 0
tests/scrippy/ssh/scrippy.rsa View File

@ -0,0 +1,38 @@
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABlwAAAAdzc2gtcn
NhAAAAAwEAAQAAAYEAtzKm9jXaP2wcyQLPcKSbP9KXd0t0lN9yjbterhrNI2NrU/RU/NG7
CDnZ5lZl7WZxxiG0AtXuXfkWEKMpv1Srg/sCIdEG5AwH1dbLDMhpoRhE5MgJJs1RwE8Bzs
FW1rbrr/mHf2ifiiPVbu8K4WboXeobdfdC5o20OCmeNjRnjdykhG/qi+gwsahfvcqpY0T5
cPqMeDspNCLPuBwu0kvXBQ3tvJEzS0Q2Uw6GbCeOmNGPQTLY5sium0TvmoKzc1/rv+DAPO
+EMVWFIwQd9cNaduI6JPAvsY8+BhKLZXxuIVJGwEp6QC9YAhlw81tN9lEN8lm64F8I7gqK
lYSN3ear9O/g+deR3zAaELquvysu05VgCbfsLxCvkPEsnMkr+XnZT40R8lvk1I/Z3Uo6Kz
wWmdhwO5ZNhCFAYCMXaAYqaZuAdvWqko6kzi2HdnPEf4NiuO0HjyG7VMCJGGaGmJDAuTsh
W/VYMvjUJif5xnI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09YpxMd49XtazLfxigTaXdIB33vNfbJ1OG5Mp3OKfzx8phXQAA
AMB5ywQhJ3k3HQq50ss4LgGVfmDYq/gxLmYRSM0Wp+B1MrB2yOrnsNx55hiCivh7JfS0Tn
q7YOBZDfAJn7vNMyfMVm7H9Y5X1MJAGuTCYQuYNUjsVaxSJ/RjMUGK70tAcgqzVKSKzoK3
1SK/x030vWPiGU0wLZ8nNtWhW0Htmi6QQ3IPBXi7UZrnTuFMFXkvf69BEmg8i5nvGuHZzM
ZVavxPVOYKr4xUcD2Wv+iYFN3R+atPJ/y0nUsVsdXlhIRh/KIAAADBAN95T0aU54HsK6hQ
uFEssrurzrkwfZpj60+0aC/BvC9vOIkD6LGzCh87GlKSQsurk1OnEWFgoUE3KRbTcvhZ3l
lcl+4gltw0JXUAo/0hGzCe0zB3ZZSe/f3s+WlEMeIu33wXb/xJODU2p67Ha23m/Kxw8uVg
Gs2BB86nPusDgOf3v4DPmmOYIZfAln+yNA6tWkKHD54adVGZxXQ/kQsYWIcmaIGRykTRSL
aqbczT/MjhHvaeFnZxUWdNIepPVqoOAwAAAMEA0dymF9MnaQcKG2Q4wu5/a6l4pxOAXFXw
OMXc8XGwJGb5Xax1JDZ4ylztgIcJs2JrdyuMKuN2+0K68zJbBEuR/qLw/I9nX5Bt4idZx5
p3kFwNNBIEADb59NSxwxGYkd2mDdpUH7HFMGmnFq+c1sl+mt8OQoLzYztHBOq+/f0XxrI4
UxCVNm+/7f6FZpYyu3T10OotTTcMZ6Ts5iYhyvylQW5XD1cLmD+ju1JKrhtlku07izYmAC
PHswj0QUu0O1FrAAAAG2RvdWdAY3liZXJsYWIucmVkYXRvbWlrLm9yZwECAwQFBgc=
-----END OPENSSH PRIVATE KEY-----

+ 6
- 3
tests/test_scrippy_core.conf View File

@ -1,5 +1,5 @@
[database]
host = postgres
host = scrippy_db
port = 5432
user = postgres
password = postgres
@ -11,7 +11,7 @@ port = 2201
user = git
repo = gitolite-admin
branch = master
ssh_cmd = "ssh -i {}/ssh/scrippy.rsa -o StrictHostKeyChecking=no"
ssh_cmd = ssh -i {}/scrippy/git/ssh/scrippy.rsa -o StrictHostKeyChecking=no
[smtp]
host = mailer
@ -27,9 +27,12 @@ password = 0123456789
host = remote
port = 2200
user = scrippy
key_file = "{}/ssh/scrippy.rsa"
keyfile = {}/scrippy/ssh/scrippy.rsa
[api]
host = api
port = 8080
endpoint = user
[templates]
filename = test_scrippy_core.txt.j2

+ 253
- 11
tests/test_scrippy_core.py View File

@ -37,7 +37,7 @@
@conf:ssh|host|str
@conf:ssh|port|int
@conf:ssh|user|str
@conf:ssh|key_file|str
@conf:ssh|keyfile|str
@conf:api|host|str
@conf:api|port|int
@conf:api|endpoint|str
@ -49,7 +49,7 @@
@args:remote_path|str|Chemin distant|1||||true
@args:remote_filename|str|nom du fichier distant|1||||true
@args:local_path|str|Chemin local|1||||true
@args:local_filename|str|nom du fichier local|1||||true
@args:pattern|str|Motif|1|.*|||false
@args:mail_recipient|choice|Adresse de courriel du destinataire|1|harry.fink@flying.circus,luiggi,vercotti@flying.circus|||true
@ -72,28 +72,163 @@
# ------------------------------------------------------------------------------
# Initialisation de l’environnement
# ------------------------------------------------------------------------------
import os
import json
import email
import shutil
import logging
import scrippy_core
import scrippy_template
import scrippy_remote
import scrippy_db
import scrippy_git
import scrippy_api
import scrippy_mail
from scrippy_db.db import Db
from scrippy_git.git import Repo
from scrippy_remote.remote import Ssh
from scrippy_api.api.client import Client
from scrippy_template.template import Renderer
from scrippy_mail.mail import Mailer, PopClient
# ------------------------------------------------------------------------------
# fonctions
# ------------------------------------------------------------------------------
def get_user_list(host, port, endpoint):
def get_api_user_list(host, port, endpoint):
"""Récupère la liste des utilisateurs à partir de l'API."""
logging.info("[+] Récupération de la liste des utilisateurs depuis l'API")
params = {}
url = "http://{}:{}/{}".format(host, port, endpoint)
client = scrippy_api.Client(verify=False)
client = Client(verify=False)
response = client.request(method="GET", url=url, params=params)
assert response.status_code == 200
users = response.json
users = response.json()['users']
for user in users:
logging.info(" '-> First name: {} / Last name: {} / Password: {}".format(user["first_name"], user["last_name"], user["password"]))
return response.json()
def add_api_user(host, port, endpoint, user):
"""Ajoute un utilisateur à l'aide de l'API."""
logging.info("[+] Ajout de l'utilisateur à l'aide de l'API")
for attr in user["user"]:
logging.info(" '-> {}: {}".format(attr, user["user"][attr]))
url = "http://{}:{}/{}".format(host, port, endpoint)
client = Client(verify=False)
response = client.request(method="PUT", url=url, data=json.dumps(user))
assert response.status_code == 200
return response.json()
def get_db_users(username, host, port, database, password):
"""Récupère la liste des utilisateurs à partir de la base de données."""
logging.info("[+] Récupération de la liste des utilisateurs depuis la base de données")
with Db(username=username, host=host, port=port, database=database, password=password) as db:
req = "select id, name, givenname, password from users order by id;"
params = None
users = db.execute(req, params)
for user in users:
logging.info(" '-> ID: {} / Last name: {} / First name: {} / Password: {}".format(user[0], user[1], user[2], user[3]))
return users
def add_db_user(username, host, port, database, password, user):
"""Ajout une utilisateur dans la base de données."""
logging.info("[+] Ajout d'un utilisateur dans la base de données")
for attr in user:
logging.info(" '-> {}".format(attr))
with Db(username=username, host=host, port=port, database=database, password=password) as db:
req = "insert into users values (DEFAULT, %s, %s, %s) returning id;"
params = user
result = db.execute(req, params=params, commit=True)
logging.info(result)
return result
def render_template(template, params):
"""Rendu de fichiers modèles."""
logging.info("[+] rendu du fichier modèle")
logging.info(" '-> {}".format(template))
base_path = scrippy_core.SCRIPPY_TEMPLATEDIR
renderer = Renderer(base_path, template)
return renderer.render(params=params)
def send_mail(host, port, rcpt, body):
"""Envoi d'un courriel."""
logging.info("[+] Envoi du courriel")
mailer = Mailer(host=host, port=port, starttls=False)
mail_from = "luiggi.vercotti@flying.circus"
mail_to = (rcpt, )
mail_subject = "Nobody expects the spanish inquisition"
mail_body = body
return mailer.send(mail_subject, mail_body, mail_to, mail_from)
def get_mail(host, port, username, password):
"""Récupération d'un courriel."""
logging.info("[+] Récupération du courriel")
pop_client = PopClient(host=host, port=port)
pop_client.connect()
pop_client.authenticate(username, password)
num_available_mails = pop_client.stat().decode()[4]
logging.info(" '-> Nombre de courriels disponibles: {}".format(num_available_mails))
assert num_available_mails == "1"
logging.info(" '-> Ok")
mail_content = pop_client.retr(1)
mail_content = email.message_from_bytes(mail_content).get_payload()
mail_content = mail_content.replace("=\r\n", "")
mail_content = mail_content.replace("\r\n.\r\n", "\n")
mail_content = "\n".join(mail_content.split("\r\n"))
logging.info(" '-> {}".format(mail_content))
return mail_content
def delete_mail(host, port, username, password, num):
"""Suppression des courriels."""
logging.info("[+] Suppression des courriels")
pop_client = PopClient(host=host, port=port)
pop_client.connect()
pop_client.authenticate(username, password)
return pop_client.dele(num)
def git_clone(repo, branch, path, env):
"""Clonage de dépôt Git."""
logging.info("[+] Clonage du dépôt:")
repo.clone(branch=branch, path=path, env=env)
def git_push(repo, message):
"""Pousse les modifications vers le dépôt distant."""
logging.info("[+] Envoi des modifications")
repo.commit_push(message)
def ssh_send_files(username, hostname, port, key_filename, local_path, remote_path, pattern):
"""Envoi de fichiers sur hôte distant."""
logging.info("[+] Envoi des fichiers via SSH")
with Ssh(username=username, hostname=hostname, port=port, key_filename=key_filename) as remote_host:
local_files = remote_host.find_local_files(local_path, pattern, recursive=True)
err = remote_host.transfer_local_files(local_files, remote_path, exit_on_error=True)
err += remote_host.delete_local_files(local_files, exit_on_error=True)
return err
def ssh_exec_cmd(username, hostname, port, key_filename, cmd):
"""Exécution d'une commande sur hôte distant."""
logging.info("[+] Exécution de la commande sur l'hôte distant")
logging.info(" '-> {}".format(cmd))
with Ssh(username=username, hostname=hostname, port=port, key_filename=key_filename) as remote_host:
stdout = remote_host.exec_command(cmd, return_stdout=True)
return stdout
def ssh_get_file(username, hostname, port, key_filename, local_path, remote_path, remote_filename):
"""Récupération de fichier depuis l'hôte distant."""
pattern = os.path.join(remote_path, remote_filename)
logging.info("[+] Récupération du fichier distant")
logging.info(" '-> {}".format(pattern))
with Ssh(username=username, hostname=hostname, port=port, key_filename=key_filename) as remote_host:
remote_files = remote_host.find_remote_files(remote_path, pattern, recursive=True, exit_on_error=True)
err = remote_host.transfer_remote_files(local_path, remote_files, exit_on_error=True)
err += remote_host.delete_remote_files(remote_files, exit_on_error=True)
return err
# ------------------------------------------------------------------------------
@ -103,6 +238,113 @@ def main(args):
with scrippy_core.ScriptContext(__file__) as _context:
config = _context.config
logging.info("[+] Test started...")
# ------------------------------------------------------------------------------
# Test du client d'API
# ------------------------------------------------------------------------------
new_user = {"user": {"first_name": "Harry", "last_name": "Fink", "password": "D3ADP4RR0T"}}
expected = {"user": new_user["user"], "method": "PUT"}
result = add_api_user(config.get("api", "host"), config.get("api", "port"), config.get("api", "endpoint"), new_user)
assert result == expected
result = get_api_user_list(config.get("api", "host"), config.get("api", "port"), config.get("api", "endpoint"))
assert len(result["users"]) == 11
assert new_user["user"] in result["users"]
# ------------------------------------------------------------------------------
# Test du client Base de données
# ------------------------------------------------------------------------------
user = ("VERCOTTI", "Luiggi", "SP4N15H1NQU1S1T10N")
result = add_db_user(config.get("database", "user"),
config.get("database", "host"),
config.get("database", "port", "int"),
config.get("database", "db"),
config.get("database", "password"),
user)
assert result[0][0] == 1
users = get_db_users(config.get("database", "user"),
config.get("database", "host"),
config.get("database", "port", "int"),
config.get("database", "db"),
config.get("database", "password"))
assert len(users) == 2 and users[0][1] == "FINK" and users[0][2] == "Harry"
assert users[1][0] == 1, users[1][1] == "VERCOTTI" and users[1][2] == "Luiggi"
# ------------------------------------------------------------------------------
# Test du moteur de modèles
# ------------------------------------------------------------------------------
params = {"user": {"first_name": users[0][2],
"last_name": users[0][1],
"password": users[0][3]},
"sender": {"first_name": users[1][2],
"last_name": users[1][1]}}
mail_body = render_template(template=config.get("templates", "filename"), params=params)
logging.info(mail_body)
with open(os.path.join(scrippy_core.SCRIPPY_TMPDIR, "message.txt"), "w") as message:
message.write(mail_body)
# ------------------------------------------------------------------------------
# Test du client SMTP
# ------------------------------------------------------------------------------
assert send_mail(host=config.get("smtp", "host"),
port=config.get("smtp", "port", "int"),
rcpt=args.mail_recipient,
body=mail_body)
# ------------------------------------------------------------------------------
# Test du client POP3
# ------------------------------------------------------------------------------
mail_content = get_mail(host=config.get("pop", "host"),
port=config.get("pop", "port", "int"),
username=config.get("pop", "user"),
password=config.get("pop", "password"))
assert mail_content.strip() == mail_body.strip()
dele_result = delete_mail(host=config.get("pop", "host"),
port=config.get("pop", "port", "int"),
username=config.get("pop", "user"),
password=config.get("pop", "password"),
num=1)
logging.info(dele_result)
assert dele_result.decode()[:3] == "+OK"
# ------------------------------------------------------------------------------
# Test du client Git
# ------------------------------------------------------------------------------
ssh_cmd = config.get("git", "ssh_cmd").format(os.path.dirname(os.path.realpath(__file__)))
local_path = os.path.join(scrippy_core.SCRIPPY_TMPDIR, config.get("git", "repo"))
ENV = {"GIT_SSH_VARIANT": "ssh",
"GIT_SSH_COMMAND": ssh_cmd}
repo = Repo(username=config.get("git", "user"),
host=config.get("git", "host"),
port=config.get("git", "port", "int"),
reponame=config.get("git", "repo"))
git_clone(repo, branch=config.get("git", "branch"), path=local_path, env=ENV)
shutil.copy(os.path.join(scrippy_core.SCRIPPY_TMPDIR, "message.txt"),
os.path.join(local_path, "message.txt"))
git_push(repo, "Harry fink is a new user")
# ------------------------------------------------------------------------------
# Test du client SSH
# ------------------------------------------------------------------------------
key_filename = config.get("ssh", "keyfile").format(os.path.dirname(os.path.realpath(__file__)))
err = ssh_send_files(username=config.get("ssh", "user"),
hostname=config.get("ssh", "host"),
port=config.get("ssh", "port", "int"),
key_filename=key_filename,
local_path=args.local_path,
remote_path=args.remote_path,
pattern=args.pattern)
assert err == 0
cmd = "find {} -type f".format(args.remote_path)
stdout = ssh_exec_cmd(username=config.get("ssh", "user"),
hostname=config.get("ssh", "host"),
port=config.get("ssh", "port", "int"),
key_filename=key_filename,
cmd=cmd)
assert stdout["exit_code"] == 0
err = ssh_get_file(username=config.get("ssh", "user"),
hostname=config.get("ssh", "host"),
port=config.get("ssh", "port", "int"),
key_filename=key_filename,
local_path=os.path.dirname(args.local_path),
remote_path=args.remote_path,
remote_filename=args.remote_filename)
assert err == 0
assert os.path.isfile(os.path.join(os.path.dirname(args.local_path), args.remote_filename))
# ------------------------------------------------------------------------------
logging.info("[+] Test finished !")


+ 8
- 0
tests/test_scrippy_core.txt.j2 View File

@ -0,0 +1,8 @@
Hello {{ params.user.first_name }},
This is your login: {{ params.user.first_name }}.{{ params.user.last_name }}
This is your password: {{ params.user.password }}
--
Best regards,
{{ params.sender.first_name }} {{ params.sender.last_name }}

Loading…
Cancel
Save