From e7a52e5607c8a47ec95330cf5f84b02b58bbea6e Mon Sep 17 00:00:00 2001 From: gitmai Date: Mon, 30 Dec 2024 11:43:37 +0100 Subject: [PATCH 1/3] Testing sample code --- test/babel.config.js | 3 + test/eslint.config.mjs | 14 +++ test/nodeSandbox.test.js | 84 +++++++++++++++ test/package.json | 24 +++++ test/python_test.py | 78 ++++++++++++++ test/test_code.sh | 228 +++++++++++++++++++++++++++++++++++++++ 6 files changed, 431 insertions(+) create mode 100644 test/babel.config.js create mode 100644 test/eslint.config.mjs create mode 100644 test/nodeSandbox.test.js create mode 100644 test/package.json create mode 100644 test/python_test.py create mode 100644 test/test_code.sh diff --git a/test/babel.config.js b/test/babel.config.js new file mode 100644 index 0000000..caedcdd --- /dev/null +++ b/test/babel.config.js @@ -0,0 +1,3 @@ +module.exports = { + presets: ["@babel/preset-env"], +}; diff --git a/test/eslint.config.mjs b/test/eslint.config.mjs new file mode 100644 index 0000000..3e68b91 --- /dev/null +++ b/test/eslint.config.mjs @@ -0,0 +1,14 @@ +import globals from "globals"; +import pluginJs from "@eslint/js"; + +/** @type {import('eslint').Linter.Config[]} */ +export default [ + { + files: ["**/*.js"], + languageOptions: { + sourceType: "module", + globals: globals.browser + } + }, + pluginJs.configs.recommended, +]; diff --git a/test/nodeSandbox.test.js b/test/nodeSandbox.test.js new file mode 100644 index 0000000..524519d --- /dev/null +++ b/test/nodeSandbox.test.js @@ -0,0 +1,84 @@ +// CIBA_Sandbox_SDK_for_Node.js.test.js +import { jest } from '@jest/globals'; +import sandboxSdk from '@telefonica/opengateway-sandbox-sdk'; +import fs from 'fs'; +import path from 'path'; + +const { DeviceLocation, Simswap } = sandboxSdk; + +jest.mock('@telefonica/opengateway-sandbox-sdk', () => ({ + DeviceLocation: jest.fn(), + Simswap: jest.fn() +})); + +const credentials = { + clientId: 'your_client_id', + clientSecret: 'your_client_secret' +}; +const CUSTOMER_PHONE_NUMBER = '+34666666666'; + +describe('DeviceLocation Client', () => { + let verifyMock; + + beforeEach(() => { + jest.clearAllMocks(); + verifyMock = jest.fn().mockReturnValue(true); + DeviceLocation.mockImplementation(() => ({ + verify: verifyMock + })); + }); + + test('should call DeviceLocation and verify with correct parameters, and log correct output', () => { + console.log = jest.fn(); + + require('./tmp/js/devicelocation/CIBA_Sandbox_SDK_for_Node.js'); + + expect(DeviceLocation).toHaveBeenCalledWith(credentials, undefined, CUSTOMER_PHONE_NUMBER); + + const latitude = 40.5150; + const longitude = -3.6640; + const radius = 10; + expect(verifyMock).toHaveBeenCalledWith(latitude, longitude, radius); + + expect(console.log).toHaveBeenCalledWith('Is the device in location? true'); + + // Imprime el valor de console.log para verlo en la salida de la consola + console.log.mock.calls.forEach(call => console.log(...call)); + }); +}); + +describe('Simswap Client', () => { + let retrieveDateMock; + + beforeEach(() => { + jest.clearAllMocks(); + retrieveDateMock = jest.fn().mockReturnValue(new Date('2023-12-25T00:00:00Z')); + Simswap.mockImplementation(() => ({ + retrieveDate: retrieveDateMock + })); + }); + + test('should call Simswap and retrieveDate with correct parameters, and log correct output', () => { + console.log = jest.fn(); + + const filePath = path.resolve(__dirname, './tmp/js/simswap/CIBA_Sandbox_SDK_for_Node.js.js'); + let fileContent = fs.readFileSync(filePath, 'utf8'); + fileContent = fileContent.replace(/await\s+/g, ''); + fs.writeFileSync(filePath, fileContent, 'utf8'); + + require('./tmp/js/simswap/CIBA_Sandbox_SDK_for_Node.js'); + + // Verifica que Simswap se llamó con los parámetros correctos + expect(Simswap).toHaveBeenCalledWith(credentials.clientId, credentials.clientSecret, CUSTOMER_PHONE_NUMBER); + + // Verifica que retrieveDate se llamó correctamente + expect(retrieveDateMock).toHaveBeenCalled(); + + // Verifica que la salida por consola es correcta + const expectedDate = new Date('2023-12-25T00:00:00Z').toLocaleString('en-GB', { timeZone: 'UTC' }); + expect(console.log).toHaveBeenCalledWith(`SIM was swapped: ${expectedDate}`); + + // Imprime el valor de console.log para verlo en la salida de la consola + console.log.mock.calls.forEach(call => console.log(...call)); + }); +}); diff --git a/test/package.json b/test/package.json new file mode 100644 index 0000000..95c9b2e --- /dev/null +++ b/test/package.json @@ -0,0 +1,24 @@ +{ + "name": "Testing sample code", + "version": "1.0.0", + "scripts": { + "test": "jest" + }, + "jest": { + "transform": { + "^.+\\.jsx?$": "babel-jest" + } + }, + "dependencies": { + "@telefonica/opengateway-sandbox-sdk": "^0.2.0-beta" + }, + "devDependencies": { + "@babel/core": "^7.26.0", + "@babel/preset-env": "^7.26.0", + "@eslint/js": "^9.17.0", + "babel-jest": "^29.7.0", + "eslint": "^9.17.0", + "globals": "^15.14.0", + "jest": "^29.0.0" + } +} diff --git a/test/python_test.py b/test/python_test.py new file mode 100644 index 0000000..f9a708a --- /dev/null +++ b/test/python_test.py @@ -0,0 +1,78 @@ +import unittest +from unittest.mock import patch, MagicMock, ANY +import importlib +import sys +import os + +class TestCibaSandbox(unittest.TestCase): + def __init__(self, methodName='runTest', module_path=None): + super(TestCibaSandbox, self).__init__(methodName) + self.module_path = module_path + + @patch('opengateway_sandbox_sdk.Simswap') + def test_simswap(self, MockSimswap): + mock_simswap_client = MockSimswap.return_value + mock_simswap_client.retrieve_date.return_value = MagicMock(strftime=lambda x: "December 23, 2024, 09:49:42 AM") + + # Importar el script después de aplicar los mocks + module = importlib.import_module(self.module_path + 'CIBA_Sandbox_SDK_for_Python') + + # Verificar que los métodos fueron llamados correctamente + MockSimswap.assert_called_once_with( + 'your_client_id', + 'your_client_secret', + '+34555555555' + ) + mock_simswap_client.retrieve_date.assert_called_once() + + # Verificar la salida del script + with patch('builtins.print') as mocked_print: + importlib.reload(module) + mocked_print.assert_called_once_with("SIM was swapped: December 23, 2024, 09:49:42 AM") + + @patch('opengateway_sandbox_sdk.DeviceLocation') + @patch('opengateway_sandbox_sdk.ClientCredentials') + def test_devicelocation(self, MockClientCredentials, MockDeviceLocation): + mock_credentials = MockClientCredentials.return_value + mock_devicelocation_client = MockDeviceLocation.return_value + mock_devicelocation_client.verify.return_value = True + + module =importlib.import_module(self.module_path + 'CIBA_Sandbox_SDK_for_Python') + + # Verificar que los métodos fueron llamados correctamente + MockClientCredentials.assert_called_once_with( + client_id = 'your_client_id', + client_secret = 'your_client_secret' + ) + MockDeviceLocation.assert_called_once_with( + credentials=mock_credentials, + phone_number=ANY + ) + mock_devicelocation_client.verify.assert_called_once_with(ANY, ANY, ANY, ANY) + + # Verificar la salida del script + with patch('builtins.print') as mocked_print: + importlib.reload(module) + mocked_print.assert_called_once_with("Is the device in location? True") + +if __name__ == '__main__': + base_dir = sys.argv[1] if len(sys.argv) > 1 else 'tmp/py' + + if not os.path.exists(base_dir): + print(f"Error: La ruta especificada '{base_dir}' no existe.") + sys.exit(1) + + suite = unittest.TestSuite() + + for api in os.listdir(base_dir): + api_dir = os.path.join(base_dir, api) + script_path = os.path.join(api_dir, 'CIBA_Sandbox_SDK_for_Python.py') + + if os.path.isfile(script_path): + module_path = base_dir.replace('/', '.') + '.' + api + '.' + TestCibaSandbox.script_path = script_path + + suite.addTest(TestCibaSandbox('test_' + api, module_path=module_path)) + + runner = unittest.TextTestRunner() + runner.run(suite) diff --git a/test/test_code.sh b/test/test_code.sh new file mode 100644 index 0000000..1c7ec32 --- /dev/null +++ b/test/test_code.sh @@ -0,0 +1,228 @@ +#!/bin/bash + +# Directorio a buscar +CATALOG_PATH="../catalog" +TMP_FOLDER="./tmp" + +# Remove previous execution data +rm -rf "$TMP_FOLDER" + +# Create Output Folder if not exist +mkdir -p "$TMP_FOLDER" + +process_node_js_file() { + awk ' + function process_node_js_file(file) { + block_found = 0 + capture_lines = 0 + line_number = 0 + block_start_line = 0 + insert_position = 0 + indent = "" + prev_indent = "" + prev_insert_position = 0 + + while ((getline line < file) > 0) { + line_number++ + if (line ~ /app\.listen\(port, \(\) => {/) { + block_found = 1 + block_start_line = line_number + capture_lines = 1 + } + + if (capture_lines) { + if (line ~ /^$/) { + capture_lines = 0 + } else { + captured_lines[line_number] = line + } + } else { + original_lines[line_number] = line + if (!block_found && (line ~ /^[[:space:]]*\}\)$/)) { + prev_insert_position = insert_position + insert_position = line_number - 1 + prev_indent = indent " " + indent = substr(line, 1, match(line, /\}\)/) - 1) + } + } + } + + if (prev_insert_position == 0) { + prev_insert_position = insert_position + } + for (i = 1; i <= prev_insert_position; i++) { + if (i in original_lines) { + print original_lines[i] > file + } + } + + for (i = block_start_line; i <= line_number; i++) { + if (i in original_lines) { + print prev_indent original_lines[i] > file + } + } + for (i = prev_insert_position + 1; i < block_start_line; i++) { + if (i in original_lines) { + print original_lines[i] > file + } + } + for (i in captured_lines) { + if (captured_lines[i] != "") { + print indent captured_lines[i] > file + } + } + } + + BEGIN { + process_node_js_file(ARGV[1]) + } + ' "$1" + } + +process_python_file() { +awk ' +function process_python_file(file) { + block_found = 0 + capture_lines = 0 + line_number = 0 + block_start_line = 0 + insert_position = 0 + indent = "" + + while ((getline line < file) > 0) { + line_number++ + if (line ~ /if __name__ == '\''__main__'\''/) { + block_found = 1 + block_start_line = line_number + insert_position = line_number - 1 + indent = " " + capture_lines = 1 + } + + if (capture_lines) { + if (line ~ /^$/) { + capture_lines = 0 + } else { + captured_lines[line_number] = line + } + } else { + original_lines[line_number] = line + } + } + + for (i = 1; i <= insert_position; i++) { + if (i in original_lines) { + print original_lines[i] > file + } + } + + for (i = insert_position; i <= line_number; i++) { + if (i in original_lines) { + if (original_lines[i] != "") { + print indent original_lines[i] > file + } + } + } + + print "" > file + print "" > file + for (i in captured_lines) { + print captured_lines[i] > file + } +} + +BEGIN { + process_python_file(ARGV[1]) +} +' "$1" + } + +for samplecode_file in $(find "$CATALOG_PATH" -maxdepth 3 -type f -name "samplecode_*.md"); do +# Extract the part of the file name between samplecode_ and .md + filename=$(basename "$samplecode_file") + name=${filename#samplecode_} + name=${name%.md} + + awk -v TMP_FOLDER="$TMP_FOLDER" -v name="$name" ' + BEGIN { + blockCount = 0 + blockCode = "" + fileName = "" + fileExt = "" + } + + /^### (Frontend|Frontend flow|Backend|Backend Flow)/ { + blockCode = $0 + gsub(/### /, "", blockCode) # Remove ### + gsub(/Backend flow/, "CIBA", blockCode) + gsub(/Frontend flow/, "Auth_code", blockCode) + gsub(/Backend/, "Auth_code", blockCode) + gsub(/Frontend/, "Auth_code", blockCode) + gsub(/ /, "_", blockCode) + } + + /^```/ { + flag = !flag + if (flag) { + sub(/^```/, "", $1) + language = $1 + title = substr($0, index($0, $2)) + gsub(/ /, "_", title) + # Define the file type mapping + fileExt = "txt" + switch (language) { + case "html": + fileExt = "html" + break + case "java": + fileExt = "java" + break + case "python": + fileExt = "py" + break + case "node": + case "javascript": + case "ecmascript": + fileExt = "js" + break + } + blockCount++ + dir = TMP_FOLDER "/" fileExt "/" name + fileName = dir "/" blockCode "_" title "." fileExt + system("mkdir -p " dir) + } else { + print "" >> fileName # Add a blank line at the end of the block + } + next + } + + flag { + print >> fileName + } + ' "$samplecode_file" + + # Fix node files to reorder code + for file in "$TMP_FOLDER/js/$name"/Auth_code*Node.js.js; do + if [ -f "$file" ]; then + process_node_js_file "$file" + fi + done + + # Fix authcode python files + for file in "$TMP_FOLDER/py/$name"/Auth_code*Python.py; do + if [ -f "$file" ]; then + process_python_file "$file" + fi + done + echo "Processing $name ==> $samplecode_file" +done + +# Execute test +echo "################### Python test ##################################" +python python_test.py +echo "################### Node test ##################################" +npx jest nodeSandbox.test.js +echo "################### Node linter ##################################" +npx eslint 'tmp/js/**/*.js' +echo "################### Python linter ##################################" +flake8 --ignore=E501,W391 tmp/py From fd58b5fee4af1a27dedd4035f73ee3d79e8230c2 Mon Sep 17 00:00:00 2001 From: gitmai Date: Mon, 30 Dec 2024 12:04:21 +0100 Subject: [PATCH 2/3] Add comments --- test/test_code.sh | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/test/test_code.sh b/test/test_code.sh index 1c7ec32..f4c422d 100644 --- a/test/test_code.sh +++ b/test/test_code.sh @@ -1,15 +1,13 @@ #!/bin/bash -# Directorio a buscar CATALOG_PATH="../catalog" TMP_FOLDER="./tmp" # Remove previous execution data rm -rf "$TMP_FOLDER" - -# Create Output Folder if not exist mkdir -p "$TMP_FOLDER" +# Function to place "API usage" code of node files in the correct place process_node_js_file() { awk ' function process_node_js_file(file) { @@ -79,6 +77,7 @@ process_node_js_file() { ' "$1" } +# Function to place "API usage" code of python files in the correct place process_python_file() { awk ' function process_python_file(file) { @@ -137,6 +136,7 @@ BEGIN { ' "$1" } +# Loop through samplecode_ files for samplecode_file in $(find "$CATALOG_PATH" -maxdepth 3 -type f -name "samplecode_*.md"); do # Extract the part of the file name between samplecode_ and .md filename=$(basename "$samplecode_file") @@ -200,15 +200,16 @@ for samplecode_file in $(find "$CATALOG_PATH" -maxdepth 3 -type f -name "samplec print >> fileName } ' "$samplecode_file" - - # Fix node files to reorder code + # At this point, we have a folder for each programming language and all the code blocks + # that have the same title have been put together. + # Reordering the code in the auth code node files for file in "$TMP_FOLDER/js/$name"/Auth_code*Node.js.js; do if [ -f "$file" ]; then process_node_js_file "$file" fi done - # Fix authcode python files + # Reordering the code in the auth code python files for file in "$TMP_FOLDER/py/$name"/Auth_code*Python.py; do if [ -f "$file" ]; then process_python_file "$file" @@ -217,7 +218,7 @@ for samplecode_file in $(find "$CATALOG_PATH" -maxdepth 3 -type f -name "samplec echo "Processing $name ==> $samplecode_file" done -# Execute test +# Execute test and linter echo "################### Python test ##################################" python python_test.py echo "################### Node test ##################################" From b06e4f92e8216a05fd58f94797d01b63b66c0a17 Mon Sep 17 00:00:00 2001 From: gitmai Date: Mon, 20 Jan 2025 08:47:55 +0100 Subject: [PATCH 3/3] Add Readme and http test --- test/README.md | 75 +++++++++++++++++++++ test/htmlForm.test.js | 137 +++++++++++++++++++++++++++++++++++++++ test/nodeSandbox.test.js | 2 +- test/package.json | 4 +- test/python_test.py | 10 +-- test/test_code.sh | 16 ++--- 6 files changed, 229 insertions(+), 15 deletions(-) create mode 100644 test/README.md create mode 100644 test/htmlForm.test.js diff --git a/test/README.md b/test/README.md new file mode 100644 index 0000000..76866b5 --- /dev/null +++ b/test/README.md @@ -0,0 +1,75 @@ +# Samplecode extractor +## Introducción + +El script `test_code.sh` es una herramienta automatizada para procesar archivos que contienen bloques de código fuente en diferentes lenguajes de programación (Java, Node.js, Python, ...), extraer esos bloques de código por lenguaje de programación y caso de uso especifico. Una vez extraido y formateado, se testean y/o se ejecutan herramientas linter, para chequear su corrección y funcionamiento en la medida de lo posible. + +## Premisas + +El script sólo analiza los archivos ubicados en el directorio `../catalog`, cuyo nombre coincide con el formato `samplecode_.md`. + +Para que el script funcione correctamente, los archivos `samplecode_*.md` deben seguir el template actual para los bloques de código, es decir, cumplir las siguientes reglas: +- Los archivos deben estar ubicados en el directorio `../catalog`. +- Los nombres de los archivos deben tener el formato `samplecode_.md`. +- Cada bloque de código debe estar delimitado por marcas de inicio y fin de bloque: + - La marca de inicio de bloque debe ser ` ``` `. + - La marca de fin de bloque debe ser ` ``` `. +- Los bloques de código deben estar correctamente indentados siguiendo las normas correspondientes para el lenguaje de programación al que corresponde. + +## Funcionamiento + +El script realiza las siguientes tareas o pasos: + +1. Elimina datos de ejecuciones anteriores y crea una carpeta temporal para almacenar archivos procesados. +2. Recorre archivos `samplecode_*.md` en el directorio `../catalog` y extrae bloques de código, organizándolos en carpetas temporales según el lenguaje de programación. +3. Reorganiza el código en los archivos Node.js y Python extraídos cuyo nombre empieza por Auth_code, para colocar el código de "uso de API" en la posición correcta en el código, ya que inicialmente la primera parte del script, solo agrupa el código de los bloques secuencialmente. +4. Ejecuta pruebas y linters para los archivos procesados. + +## Requisitos + +Para ejecutar este script, necesitas tener instalados los siguientes programas y herramientas: + +- **Bash**: Un shell compatible con Bash. +- **Node.js**: Incluyendo `npx` y `jest` para ejecutar pruebas y linters. +- **Python**: Incluyendo `flake8` para ejecutar linters. + +## Instalación + +1. **Instalar Node.js y npm**: + - Puedes descargar e instalar Node.js desde nodejs.org. + - npm se instala automáticamente con Node.js. + +2. **Instalar las dependencias del proyecto**: + + - Navega al directorio del proyecto `test`, donde se encuentra el archivo package.json. + - Ejecuta el siguiente comando para instalar las dependencias: + ```bash + npm install + ``` + +3. **Instalar Python**: + - Puedes descargar e instalar Python desde python.org. + +4. **Instalar flake8**: + - Ejecuta el siguiente comando para instalar `flake8`: + ```bash + pip install flake8 + ``` + +## Ejecución + +Para ejecutar el script `test_code.sh`, sigue estos pasos: + +1. Asegúrate de que los requisitos estén instalados. +2. Navega al directorio `test` donde se encuentra el script `test_code.sh`. +3. Ejecuta el script con el siguiente comando: + ```bash + ./test_code.sh + ``` +El script procesará los archivos de código fuente, reorganizará los bloques de código y ejecutará las pruebas y linters correspondientes. Los resultados se mostrarán en la terminal. + +Notas: +* Asegúrate de tener permisos de ejecución para el script. Si no los tienes, puedes otorgarlos con el siguiente comando: + ```bash + chmod +x test_code.sh + ``` +* Analiza la salida del script y ten encuenta que algunos de los warnings tiene sentido no corregirlos. Por ejemplo, algunas variables no se utilizan en el código pero se mantienen para que los usuarios tengan claro que existen y se pueden utilizar. diff --git a/test/htmlForm.test.js b/test/htmlForm.test.js new file mode 100644 index 0000000..2745358 --- /dev/null +++ b/test/htmlForm.test.js @@ -0,0 +1,137 @@ +const { JSDOM } = require('jsdom'); +const fs = require('fs'); +const path = require('path'); +const glob = require('glob'); + +describe('API Request Form', () => { + let documents = []; + let api = []; + + const apiValues = { + devicelocation: { + scope: 'dpv:FraudPreventionAndDetection#device-location-read', + redirectUri: 'https://my_app_server/device-location-callback', + phoneNumberInput: 'phone_number', + phoneNumberValue: '+34666666666' + }, + devicestatus: { + scope: 'dpv:FraudPreventionAndDetection#device-status-roaming-read', + redirectUri: 'https://my_app_server/device-status-callback', + phoneNumberInput: 'phone_number', + phoneNumberValue: '+34777777777' + }, + deviceswap: { + scope: 'dpv:FraudPreventionAndDetection#device-swap', + redirectUri: 'https://my_app_server/deviceswap-callback', + phoneNumberInput: 'phone_number', + phoneNumberValue: '+34333333333' + }, + knowyourcustomer: { + scope: 'dpv:FraudPreventionAndDetection#kyc-match:match', + redirectUri: 'https://my_app_server/kyc-match-callback', + phoneNumberInput: 'phone_number', + phoneNumberValue: '+34666666666' + }, + numberverification: { + scope: 'dpv:FraudPreventionAndDetection#number-verification-verify-read', + redirectUri: '/numberverification-callback', + phoneNumberInput: 'state', + phoneNumberValue: '+34555555555' + }, + qod: { + scope: 'dpv:RequestedServiceProvision#qod', + redirectUri: '/qod-auth-callback' + }, + simswap: { + scope: 'dpv:FraudPreventionAndDetection#sim-swap', + redirectUri: '/simswap-callback', + phoneNumberInput: 'state', + phoneNumberValue: '+34555555555' + } + }; + + beforeAll((done) => { + try { + const files = glob.sync('./tmp/html/**/Auth_code_HTML_*.html'); + files.forEach(file => { + const filePath = path.resolve(__dirname, file); + const html = fs.readFileSync(filePath, 'utf8'); + const dom = new JSDOM(html); + documents.push(dom.window.document); + + const dirPath = path.dirname(filePath); + const lastSubdirectory = path.basename(dirPath); + api.push(lastSubdirectory); + }); + done(); + } catch (err) { + console.error('Error:', err); + } + }); + + test('form should have correct action URL', () => { + documents.forEach((document, index) => { + try { + const form = document.getElementById('apiRequestForm'); + expect(form.action).toBe('https://opengateway.aggregator.com/authorize', `Error in file of API:: ${api[index]}`); + } catch (error) { + console.error(`Error in file of API:: ${api[index]}`); + throw error; + } + }); + }); + + test('form should use GET method', () => { + documents.forEach((document, index) => { + try { + const form = document.getElementById('apiRequestForm'); + expect(form.method.toLowerCase()).toBe('get'); + } catch (error) { + console.error(`Error in file of API:: ${api[index]}`); + throw error; + } + }); + }); + + test('hidden inputs should have correct values', () => { + documents.forEach((document, index) => { + const clientIdInput = document.querySelector('input[name="client_id"]'); + const responseTypeInput = document.querySelector('input[name="response_type"]'); + const scopeInput = document.querySelector('input[name="scope"]'); + const redirectUriInput = document.querySelector('input[name="redirect_uri"]'); + try { + const apiValue = apiValues[api[index]]; + + expect(clientIdInput.value).toBe('my-app-id'); + expect(responseTypeInput.value).toBe('code'); + expect(scopeInput.value).toBe(apiValue.scope); + expect(redirectUriInput.value).toBe(apiValue.redirectUri); + } catch (error) { + console.error(`Error in file of API:: ${api[index]}`); + throw error; + } + }); + }); + + test('phone number input should have correct value and be required', () => { + documents.forEach((document, index) => { + const apiValue = apiValues[api[index]]; + if (api[index] === 'qod') { + console.log('Skipping test for API::', api[index]); + return; + } + const phoneNumberInput = document.getElementById(apiValue.phoneNumberInput); + try { + if (!phoneNumberInput) { + console.error(`Phone number input not found in API: ${api[index]}`); + return; + } + expect(phoneNumberInput.value).toBe(apiValue.phoneNumberValue); + expect(phoneNumberInput.required).toBe(true); + } catch (error) { + console.error(`Error in file of API:: ${api[index]}`); + throw error; + } + }); + }); +}); diff --git a/test/nodeSandbox.test.js b/test/nodeSandbox.test.js index 524519d..ea4d633 100644 --- a/test/nodeSandbox.test.js +++ b/test/nodeSandbox.test.js @@ -67,7 +67,7 @@ describe('Simswap Client', () => { fs.writeFileSync(filePath, fileContent, 'utf8'); require('./tmp/js/simswap/CIBA_Sandbox_SDK_for_Node.js'); - + // Verifica que Simswap se llamó con los parámetros correctos expect(Simswap).toHaveBeenCalledWith(credentials.clientId, credentials.clientSecret, CUSTOMER_PHONE_NUMBER); diff --git a/test/package.json b/test/package.json index 95c9b2e..e5f410b 100644 --- a/test/package.json +++ b/test/package.json @@ -18,7 +18,9 @@ "@eslint/js": "^9.17.0", "babel-jest": "^29.7.0", "eslint": "^9.17.0", + "glob": "^10.4.5", "globals": "^15.14.0", - "jest": "^29.0.0" + "jest": "^29.0.0", + "jsdom": "^22.1.0" } } diff --git a/test/python_test.py b/test/python_test.py index f9a708a..c06bd9f 100644 --- a/test/python_test.py +++ b/test/python_test.py @@ -8,15 +8,15 @@ class TestCibaSandbox(unittest.TestCase): def __init__(self, methodName='runTest', module_path=None): super(TestCibaSandbox, self).__init__(methodName) self.module_path = module_path - + @patch('opengateway_sandbox_sdk.Simswap') def test_simswap(self, MockSimswap): mock_simswap_client = MockSimswap.return_value mock_simswap_client.retrieve_date.return_value = MagicMock(strftime=lambda x: "December 23, 2024, 09:49:42 AM") - + # Importar el script después de aplicar los mocks module = importlib.import_module(self.module_path + 'CIBA_Sandbox_SDK_for_Python') - + # Verificar que los métodos fueron llamados correctamente MockSimswap.assert_called_once_with( 'your_client_id', @@ -38,7 +38,7 @@ def test_devicelocation(self, MockClientCredentials, MockDeviceLocation): mock_devicelocation_client.verify.return_value = True module =importlib.import_module(self.module_path + 'CIBA_Sandbox_SDK_for_Python') - + # Verificar que los métodos fueron llamados correctamente MockClientCredentials.assert_called_once_with( client_id = 'your_client_id', @@ -67,7 +67,7 @@ def test_devicelocation(self, MockClientCredentials, MockDeviceLocation): for api in os.listdir(base_dir): api_dir = os.path.join(base_dir, api) script_path = os.path.join(api_dir, 'CIBA_Sandbox_SDK_for_Python.py') - + if os.path.isfile(script_path): module_path = base_dir.replace('/', '.') + '.' + api + '.' TestCibaSandbox.script_path = script_path diff --git a/test/test_code.sh b/test/test_code.sh index f4c422d..cce64d4 100644 --- a/test/test_code.sh +++ b/test/test_code.sh @@ -27,7 +27,7 @@ process_node_js_file() { block_start_line = line_number capture_lines = 1 } - + if (capture_lines) { if (line ~ /^$/) { capture_lines = 0 @@ -53,7 +53,7 @@ process_node_js_file() { print original_lines[i] > file } } - + for (i = block_start_line; i <= line_number; i++) { if (i in original_lines) { print prev_indent original_lines[i] > file @@ -97,7 +97,7 @@ function process_python_file(file) { indent = " " capture_lines = 1 } - + if (capture_lines) { if (line ~ /^$/) { capture_lines = 0 @@ -114,7 +114,7 @@ function process_python_file(file) { print original_lines[i] > file } } - + for (i = insert_position; i <= line_number; i++) { if (i in original_lines) { if (original_lines[i] != "") { @@ -153,7 +153,7 @@ for samplecode_file in $(find "$CATALOG_PATH" -maxdepth 3 -type f -name "samplec /^### (Frontend|Frontend flow|Backend|Backend Flow)/ { blockCode = $0 - gsub(/### /, "", blockCode) # Remove ### + gsub(/### /, "", blockCode) # Remove ### gsub(/Backend flow/, "CIBA", blockCode) gsub(/Frontend flow/, "Auth_code", blockCode) gsub(/Backend/, "Auth_code", blockCode) @@ -200,7 +200,7 @@ for samplecode_file in $(find "$CATALOG_PATH" -maxdepth 3 -type f -name "samplec print >> fileName } ' "$samplecode_file" - # At this point, we have a folder for each programming language and all the code blocks + # At this point, we have a folder for each programming language and all the code blocks # that have the same title have been put together. # Reordering the code in the auth code node files for file in "$TMP_FOLDER/js/$name"/Auth_code*Node.js.js; do @@ -221,8 +221,8 @@ done # Execute test and linter echo "################### Python test ##################################" python python_test.py -echo "################### Node test ##################################" -npx jest nodeSandbox.test.js +echo "################### Node & html test ##################################" +npx jest echo "################### Node linter ##################################" npx eslint 'tmp/js/**/*.js' echo "################### Python linter ##################################"