Skip to content

Commit d5348de

Browse files
committed
Testing sample code
1 parent ef2cb8b commit d5348de

File tree

6 files changed

+431
-0
lines changed

6 files changed

+431
-0
lines changed

test/babel.config.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
module.exports = {
2+
presets: ["@babel/preset-env"],
3+
};

test/eslint.config.mjs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import globals from "globals";
2+
import pluginJs from "@eslint/js";
3+
4+
/** @type {import('eslint').Linter.Config[]} */
5+
export default [
6+
{
7+
files: ["**/*.js"],
8+
languageOptions: {
9+
sourceType: "module",
10+
globals: globals.browser
11+
}
12+
},
13+
pluginJs.configs.recommended,
14+
];

test/nodeSandbox.test.js

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
// CIBA_Sandbox_SDK_for_Node.js.test.js
2+
import { jest } from '@jest/globals';
3+
import sandboxSdk from '@telefonica/opengateway-sandbox-sdk';
4+
import fs from 'fs';
5+
import path from 'path';
6+
7+
const { DeviceLocation, Simswap } = sandboxSdk;
8+
9+
jest.mock('@telefonica/opengateway-sandbox-sdk', () => ({
10+
DeviceLocation: jest.fn(),
11+
Simswap: jest.fn()
12+
}));
13+
14+
const credentials = {
15+
clientId: 'your_client_id',
16+
clientSecret: 'your_client_secret'
17+
};
18+
const CUSTOMER_PHONE_NUMBER = '+34666666666';
19+
20+
describe('DeviceLocation Client', () => {
21+
let verifyMock;
22+
23+
beforeEach(() => {
24+
jest.clearAllMocks();
25+
verifyMock = jest.fn().mockReturnValue(true);
26+
DeviceLocation.mockImplementation(() => ({
27+
verify: verifyMock
28+
}));
29+
});
30+
31+
test('should call DeviceLocation and verify with correct parameters, and log correct output', () => {
32+
console.log = jest.fn();
33+
34+
require('./tmp/js/devicelocation/CIBA_Sandbox_SDK_for_Node.js');
35+
36+
expect(DeviceLocation).toHaveBeenCalledWith(credentials, undefined, CUSTOMER_PHONE_NUMBER);
37+
38+
const latitude = 40.5150;
39+
const longitude = -3.6640;
40+
const radius = 10;
41+
expect(verifyMock).toHaveBeenCalledWith(latitude, longitude, radius);
42+
43+
expect(console.log).toHaveBeenCalledWith('Is the device in location? true');
44+
45+
// Imprime el valor de console.log para verlo en la salida de la consola
46+
console.log.mock.calls.forEach(call => console.log(...call));
47+
});
48+
});
49+
50+
describe('Simswap Client', () => {
51+
let retrieveDateMock;
52+
53+
beforeEach(() => {
54+
jest.clearAllMocks();
55+
retrieveDateMock = jest.fn().mockReturnValue(new Date('2023-12-25T00:00:00Z'));
56+
Simswap.mockImplementation(() => ({
57+
retrieveDate: retrieveDateMock
58+
}));
59+
});
60+
61+
test('should call Simswap and retrieveDate with correct parameters, and log correct output', () => {
62+
console.log = jest.fn();
63+
64+
const filePath = path.resolve(__dirname, './tmp/js/simswap/CIBA_Sandbox_SDK_for_Node.js.js');
65+
let fileContent = fs.readFileSync(filePath, 'utf8');
66+
fileContent = fileContent.replace(/await\s+/g, '');
67+
fs.writeFileSync(filePath, fileContent, 'utf8');
68+
69+
require('./tmp/js/simswap/CIBA_Sandbox_SDK_for_Node.js');
70+
71+
// Verifica que Simswap se llamó con los parámetros correctos
72+
expect(Simswap).toHaveBeenCalledWith(credentials.clientId, credentials.clientSecret, CUSTOMER_PHONE_NUMBER);
73+
74+
// Verifica que retrieveDate se llamó correctamente
75+
expect(retrieveDateMock).toHaveBeenCalled();
76+
77+
// Verifica que la salida por consola es correcta
78+
const expectedDate = new Date('2023-12-25T00:00:00Z').toLocaleString('en-GB', { timeZone: 'UTC' });
79+
expect(console.log).toHaveBeenCalledWith(`SIM was swapped: ${expectedDate}`);
80+
81+
// Imprime el valor de console.log para verlo en la salida de la consola
82+
console.log.mock.calls.forEach(call => console.log(...call));
83+
});
84+
});

test/package.json

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
{
2+
"name": "Testing sample code",
3+
"version": "1.0.0",
4+
"scripts": {
5+
"test": "jest"
6+
},
7+
"jest": {
8+
"transform": {
9+
"^.+\\.jsx?$": "babel-jest"
10+
}
11+
},
12+
"dependencies": {
13+
"@telefonica/opengateway-sandbox-sdk": "^0.2.0-beta"
14+
},
15+
"devDependencies": {
16+
"@babel/core": "^7.26.0",
17+
"@babel/preset-env": "^7.26.0",
18+
"@eslint/js": "^9.17.0",
19+
"babel-jest": "^29.7.0",
20+
"eslint": "^9.17.0",
21+
"globals": "^15.14.0",
22+
"jest": "^29.0.0"
23+
}
24+
}

test/python_test.py

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
import unittest
2+
from unittest.mock import patch, MagicMock, ANY
3+
import importlib
4+
import sys
5+
import os
6+
7+
class TestCibaSandbox(unittest.TestCase):
8+
def __init__(self, methodName='runTest', module_path=None):
9+
super(TestCibaSandbox, self).__init__(methodName)
10+
self.module_path = module_path
11+
12+
@patch('opengateway_sandbox_sdk.Simswap')
13+
def test_simswap(self, MockSimswap):
14+
mock_simswap_client = MockSimswap.return_value
15+
mock_simswap_client.retrieve_date.return_value = MagicMock(strftime=lambda x: "December 23, 2024, 09:49:42 AM")
16+
17+
# Importar el script después de aplicar los mocks
18+
module = importlib.import_module(self.module_path + 'CIBA_Sandbox_SDK_for_Python')
19+
20+
# Verificar que los métodos fueron llamados correctamente
21+
MockSimswap.assert_called_once_with(
22+
'your_client_id',
23+
'your_client_secret',
24+
'+34555555555'
25+
)
26+
mock_simswap_client.retrieve_date.assert_called_once()
27+
28+
# Verificar la salida del script
29+
with patch('builtins.print') as mocked_print:
30+
importlib.reload(module)
31+
mocked_print.assert_called_once_with("SIM was swapped: December 23, 2024, 09:49:42 AM")
32+
33+
@patch('opengateway_sandbox_sdk.DeviceLocation')
34+
@patch('opengateway_sandbox_sdk.ClientCredentials')
35+
def test_devicelocation(self, MockClientCredentials, MockDeviceLocation):
36+
mock_credentials = MockClientCredentials.return_value
37+
mock_devicelocation_client = MockDeviceLocation.return_value
38+
mock_devicelocation_client.verify.return_value = True
39+
40+
module =importlib.import_module(self.module_path + 'CIBA_Sandbox_SDK_for_Python')
41+
42+
# Verificar que los métodos fueron llamados correctamente
43+
MockClientCredentials.assert_called_once_with(
44+
client_id = 'your_client_id',
45+
client_secret = 'your_client_secret'
46+
)
47+
MockDeviceLocation.assert_called_once_with(
48+
credentials=mock_credentials,
49+
phone_number=ANY
50+
)
51+
mock_devicelocation_client.verify.assert_called_once_with(ANY, ANY, ANY, ANY)
52+
53+
# Verificar la salida del script
54+
with patch('builtins.print') as mocked_print:
55+
importlib.reload(module)
56+
mocked_print.assert_called_once_with("Is the device in location? True")
57+
58+
if __name__ == '__main__':
59+
base_dir = sys.argv[1] if len(sys.argv) > 1 else 'tmp/py'
60+
61+
if not os.path.exists(base_dir):
62+
print(f"Error: La ruta especificada '{base_dir}' no existe.")
63+
sys.exit(1)
64+
65+
suite = unittest.TestSuite()
66+
67+
for api in os.listdir(base_dir):
68+
api_dir = os.path.join(base_dir, api)
69+
script_path = os.path.join(api_dir, 'CIBA_Sandbox_SDK_for_Python.py')
70+
71+
if os.path.isfile(script_path):
72+
module_path = base_dir.replace('/', '.') + '.' + api + '.'
73+
TestCibaSandbox.script_path = script_path
74+
75+
suite.addTest(TestCibaSandbox('test_' + api, module_path=module_path))
76+
77+
runner = unittest.TextTestRunner()
78+
runner.run(suite)

0 commit comments

Comments
 (0)