Skip to content

Commit 9adffbc

Browse files
committed
fix init deploy test
1 parent ad7521d commit 9adffbc

6 files changed

Lines changed: 221 additions & 125 deletions

File tree

e2e-tests/conftest.py

Lines changed: 91 additions & 72 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,16 @@
1+
import json
2+
import logging
13
import os
2-
from typing import Dict
3-
import pytest
4+
import random
45
import subprocess
5-
import logging
6-
import yaml
7-
import json
86
import time
9-
import random
10-
11-
from pathlib import Path
127
from concurrent.futures import ThreadPoolExecutor
8+
from pathlib import Path
9+
from typing import Dict
1310

14-
from lib import tools
15-
from lib import k8s_collector
11+
import pytest
12+
import yaml
13+
from lib import k8s_collector, tools
1614

1715
logging.getLogger("pytest_dependency").setLevel(logging.WARNING)
1816
logger = logging.getLogger(__name__)
@@ -27,12 +25,13 @@ def pytest_runtest_makereport(item: pytest.Item, call: pytest.CallInfo) -> None:
2725
report = outcome.get_result()
2826

2927
if report.when == "call" and report.failed and _current_namespace:
30-
logger.info(f"Test failed, collecting K8s resources from {_current_namespace}")
31-
try:
32-
custom_resources = ["psmdb", "psmdb-backup", "psmdb-restore"]
33-
k8s_collector.collect_resources(_current_namespace, custom_resources)
34-
except Exception as e:
35-
logger.warning(f"Failed to collect K8s resources: {e}")
28+
if os.environ.get("COLLECT_K8S_ON_FAILURE") == "1":
29+
logger.info(f"Test failed, collecting K8s resources from {_current_namespace}")
30+
try:
31+
custom_resources = ["psmdb", "psmdb-backup", "psmdb-restore"]
32+
k8s_collector.collect_resources(_current_namespace, custom_resources)
33+
except Exception as e:
34+
logger.warning(f"Failed to collect K8s resources: {e}")
3635

3736

3837
@pytest.fixture(scope="session", autouse=True)
@@ -70,8 +69,9 @@ def setup_env_vars() -> None:
7069
"CLEAN_NAMESPACE": "0",
7170
"DELETE_CRD_ON_START": "0",
7271
"SKIP_DELETE": "1",
73-
"SKIP_BACKUPS_TO_AWS_GCP_AZURE": "1",
72+
"SKIP_BACKUPS_TO_AWS_GCP_AZURE": tools.get_cloud_secret_default(),
7473
"UPDATE_COMPARE_FILES": "0",
74+
"COLLECT_K8S_ON_FAILURE": "1",
7575
}
7676

7777
for key, value in defaults.items():
@@ -82,19 +82,19 @@ def setup_env_vars() -> None:
8282

8383

8484
@pytest.fixture(scope="class")
85-
def test_paths(request: pytest.FixtureRequest) -> Dict[str, Path]:
85+
def test_paths(request: pytest.FixtureRequest) -> Dict[str, str]:
8686
"""Fixture to provide paths relative to the test file."""
8787
test_file = Path(request.fspath)
8888
test_dir = test_file.parent
8989
conf_dir = test_dir.parent / "conf"
9090
src_dir = test_dir.parent.parent
9191

92-
return {"test_file": test_file, "test_dir": test_dir, "conf_dir": conf_dir, "src_dir": src_dir}
92+
return {"test_file": str(test_file), "test_dir": str(test_dir), "conf_dir": str(conf_dir), "src_dir": str(src_dir)}
9393

9494

9595
@pytest.fixture(scope="class")
96-
def create_namespace():
97-
def _create_namespace(namespace):
96+
def create_namespace() -> callable:
97+
def _create_namespace(namespace: str) -> str:
9898
"""Create kubernetes namespace and clean up if exists."""
9999
operator_ns = os.environ.get("OPERATOR_NS")
100100

@@ -160,7 +160,7 @@ def _create_namespace(namespace):
160160

161161

162162
@pytest.fixture(scope="class")
163-
def create_infra(test_paths: Dict[str, Path], create_namespace):
163+
def create_infra(test_paths: Dict[str, str], create_namespace):
164164
global _current_namespace
165165
created_namespaces = []
166166

@@ -188,7 +188,6 @@ def _create_infra(test_name):
188188
yield _create_infra
189189

190190
# Teardown code
191-
global _current_namespace
192191
_current_namespace = None
193192

194193
if os.environ.get("SKIP_DELETE") == "1":
@@ -248,30 +247,16 @@ def cleanup_crd() -> None:
248247
futures.append(executor.submit(cleanup_crd))
249248

250249
# Clean up all created namespaces
251-
namespace_commands = []
252-
for namespace in created_namespaces:
253-
namespace_commands.append(
254-
["delete", "--grace-period=0", "--force", "namespace", namespace, "--ignore-not-found"]
255-
)
256-
250+
namespaces_to_delete = created_namespaces.copy()
257251
if os.environ.get("OPERATOR_NS"):
258-
namespace_commands.append(
259-
[
260-
"delete",
261-
"--grace-period=0",
262-
"--force",
263-
"namespace",
264-
os.environ.get("OPERATOR_NS"),
265-
"--ignore-not-found",
266-
]
267-
)
252+
namespaces_to_delete.append(os.environ.get("OPERATOR_NS"))
268253

269-
for cmd in namespace_commands:
270-
run_cmd(cmd)
254+
for ns in namespaces_to_delete:
255+
run_cmd(["delete", "--grace-period=0", "--force", "namespace", ns, "--ignore-not-found"])
271256

272257

273258
@pytest.fixture(scope="class")
274-
def deploy_chaos_mesh(namespace):
259+
def deploy_chaos_mesh(namespace: str) -> None:
275260
"""Deploy Chaos Mesh and clean up after tests."""
276261
try:
277262
subprocess.run(
@@ -339,7 +324,7 @@ def deploy_chaos_mesh(namespace):
339324

340325

341326
@pytest.fixture(scope="class")
342-
def deploy_cert_manager():
327+
def deploy_cert_manager() -> None:
343328
"""Deploy Cert Manager and clean up after tests."""
344329
logger.info("Deploying cert-manager")
345330
cert_manager_url = f"https://github.com/cert-manager/cert-manager/releases/download/v{os.environ.get('CERT_MANAGER_VER')}/cert-manager.yaml"
@@ -376,7 +361,7 @@ def deploy_cert_manager():
376361

377362

378363
@pytest.fixture(scope="class")
379-
def deploy_minio():
364+
def deploy_minio() -> None:
380365
"""Deploy MinIO and clean up after tests."""
381366
service_name = "minio-service"
382367
bucket = "operator-testing"
@@ -389,30 +374,52 @@ def deploy_minio():
389374

390375
endpoint = f"http://{service_name}:9000"
391376
minio_args = [
392-
"helm", "install", service_name, "minio/minio",
393-
"--version", os.environ.get("MINIO_VER"),
394-
"--set", "replicas=1",
395-
"--set", "mode=standalone",
396-
"--set", "resources.requests.memory=256Mi",
397-
"--set", "rootUser=rootuser",
398-
"--set", "rootPassword=rootpass123",
399-
"--set", "users[0].accessKey=some-access-key",
400-
"--set", "users[0].secretKey=some-secret-key",
401-
"--set", "users[0].policy=consoleAdmin",
402-
"--set", "service.type=ClusterIP",
403-
"--set", "configPathmc=/tmp/",
404-
"--set", "securityContext.enabled=false",
405-
"--set", "persistence.size=2G",
406-
"--set", f"fullnameOverride={service_name}",
407-
"--set", "serviceAccount.create=true",
408-
"--set", f"serviceAccount.name={service_name}-sa",
377+
"helm",
378+
"install",
379+
service_name,
380+
"minio/minio",
381+
"--version",
382+
os.environ.get("MINIO_VER"),
383+
"--set",
384+
"replicas=1",
385+
"--set",
386+
"mode=standalone",
387+
"--set",
388+
"resources.requests.memory=256Mi",
389+
"--set",
390+
"rootUser=rootuser",
391+
"--set",
392+
"rootPassword=rootpass123",
393+
"--set",
394+
"users[0].accessKey=some-access-key",
395+
"--set",
396+
"users[0].secretKey=some-secret-key",
397+
"--set",
398+
"users[0].policy=consoleAdmin",
399+
"--set",
400+
"service.type=ClusterIP",
401+
"--set",
402+
"configPathmc=/tmp/",
403+
"--set",
404+
"securityContext.enabled=false",
405+
"--set",
406+
"persistence.size=2G",
407+
"--set",
408+
f"fullnameOverride={service_name}",
409+
"--set",
410+
"serviceAccount.create=true",
411+
"--set",
412+
f"serviceAccount.name={service_name}-sa",
409413
]
410414

411415
tools.retry(lambda: subprocess.run(minio_args, check=True), max_attempts=10, delay=60)
412416

413417
minio_pod = tools.kubectl_bin(
414-
"get", "pods", f"--selector=release={service_name}",
415-
"-o", "jsonpath={.items[].metadata.name}"
418+
"get",
419+
"pods",
420+
f"--selector=release={service_name}",
421+
"-o",
422+
"jsonpath={.items[].metadata.name}",
416423
).strip()
417424
tools.wait_pod(minio_pod)
418425

@@ -422,19 +429,31 @@ def deploy_minio():
422429
"config", "view", "--minify", "-o", "jsonpath={..namespace}"
423430
).strip()
424431
tools.kubectl_bin(
425-
"create", "svc", "-n", operator_ns, "externalname", service_name,
432+
"create",
433+
"svc",
434+
"-n",
435+
operator_ns,
436+
"externalname",
437+
service_name,
426438
f"--external-name={service_name}.{namespace}.svc.cluster.local",
427-
"--tcp=9000", check=False
439+
"--tcp=9000",
440+
check=False,
428441
)
429442

430443
logger.info(f"Creating MinIO bucket: {bucket}")
431444
tools.kubectl_bin(
432-
"run", "-i", "--rm", "aws-cli",
433-
"--image=perconalab/awscli", "--restart=Never",
434-
"--", "bash", "-c",
435-
f"AWS_ACCESS_KEY_ID=some-access-key "
436-
f"AWS_SECRET_ACCESS_KEY=some-secret-key "
437-
f"AWS_DEFAULT_REGION=us-east-1 "
445+
"run",
446+
"-i",
447+
"--rm",
448+
"aws-cli",
449+
"--image=perconalab/awscli",
450+
"--restart=Never",
451+
"--",
452+
"bash",
453+
"-c",
454+
"AWS_ACCESS_KEY_ID=some-access-key"
455+
"AWS_SECRET_ACCESS_KEY=some-secret-key"
456+
"AWS_DEFAULT_REGION=us-east-1"
438457
f"/usr/bin/aws --no-verify-ssl --endpoint-url {endpoint} s3 mb s3://{bucket}",
439458
)
440459

@@ -450,7 +469,7 @@ def deploy_minio():
450469

451470

452471
@pytest.fixture(scope="class")
453-
def psmdb_client(test_paths: Dict[str, Path]) -> tools.MongoManager:
472+
def psmdb_client(test_paths: Dict[str, str]) -> tools.MongoManager:
454473
"""Deploy and get the client pod name."""
455474
tools.kubectl_bin("apply", "-f", f"{test_paths['conf_dir']}/client-70.yml")
456475

e2e-tests/finalizer/test_finalizer.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
1-
from pathlib import Path
2-
import pytest
31
import logging
2+
from pathlib import Path
3+
from typing import Callable, Dict, Union
44

5+
import pytest
56
from lib import tools
6-
from typing import Callable, Dict, Union
77

88
logger = logging.getLogger(__name__)
99

e2e-tests/init-deploy/test_init_deploy.py

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
#!/usr/bin/env python3
22

3-
import pytest
43
import logging
4+
import time
5+
from typing import Callable, Dict, Union
56

7+
import pytest
68
from lib import tools
7-
from typing import Callable, Dict, Union
89

910
logger = logging.getLogger(__name__)
1011

@@ -170,8 +171,10 @@ def test_primary_failover(self, config, test_paths, psmdb_client):
170171
@pytest.mark.dependency(depends=["TestInitDeploy::test_primary_failover"])
171172
def test_create_second_cluster(self, config, test_paths):
172173
"""Check if possible to create second cluster"""
174+
tools.apply_s3_storage_secrets(test_paths["conf_dir"])
173175
tools.apply_cluster(f"{test_paths['test_dir']}/conf/{config['cluster2']}.yml")
174176
tools.wait_for_running(config["cluster2"], 3)
177+
175178
tools.compare_kubectl(
176179
test_paths["test_dir"], f"statefulset/{config['cluster2']}", config["namespace"]
177180
)
@@ -204,6 +207,22 @@ def test_second_cluster_data_operations(self, config, test_paths, psmdb_client):
204207
)
205208

206209
@pytest.mark.dependency(depends=["TestInitDeploy::test_second_cluster_data_operations"])
210+
def test_connection_count_with_backup(self, config, psmdb_client):
211+
"""Check number of connections doesn't exceed maximum with backup enabled"""
212+
max_conn = 50
213+
time.sleep(300) # Wait for backup agent connections
214+
215+
conn_count = int(
216+
psmdb_client.run_mongosh(
217+
"db.serverStatus().connections.current",
218+
f"clusterAdmin:clusterAdmin123456@{config['cluster2']}.{config['namespace']}",
219+
).strip()
220+
)
221+
assert conn_count <= max_conn, (
222+
f"Connection count {conn_count} exceeds maximum {max_conn} with backup enabled"
223+
)
224+
225+
@pytest.mark.dependency(depends=["TestInitDeploy::test_connection_count_with_backup"])
207226
def test_log_files_exist(self, config):
208227
"""Check if mongod log files exist in pod"""
209228
result = tools.kubectl_bin(

e2e-tests/lib/k8s_collector.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,13 @@
22

33
import os
44
import re
5+
import subprocess
56
import sys
67
import tarfile
7-
import subprocess
8-
from datetime import datetime
98
from concurrent.futures import ThreadPoolExecutor, as_completed
9+
from datetime import datetime
1010
from typing import List, Optional
1111

12-
1312
REPORTS_DIR = os.path.join(os.path.dirname(__file__), "..", "reports")
1413

1514

0 commit comments

Comments
 (0)