Saturday, July 13, 2024

Java Unit Test MCQ

 Question 1


Which framework is most commonly used for unit testing in Java?


JUnit  

TestNG  

Mockito  

Selenium

Answer:  


JUnit



Question 2

In JUnit 5, which annotation is used to indicate a test method?


@TestCase  

@RunWith  

@Test  

@Before

Answer:  


@Test



Question 3

Which JUnit annotation is used to execute some code before each test method?


@BeforeAll  

@After  

@BeforeEach  

@BeforeTest

Answer:  


@BeforeEach



Question 4

Which method in JUnit is used to check if two objects are equal?


assertSame  

assertTrue  

assertEquals  

assertNotNull

Answer:  


assertEquals



Question 5

Which of the following is a mocking framework often used in Java unit tests?


TestNG  

Mockito  

JUnit  

Cucumber

Answer:  


Mockito



Question 6

In Mockito, which method is used to create a mock object?


mock()  

createMock()  

mockObject()  

newMock()

Answer:  


mock()



Question 7

What does the @Mock annotation do in Mockito?


It creates a real object  

It creates a mock object  

It verifies a method call  

It initializes a mock object

Answer:  


It creates a mock object



Question 8

Which JUnit annotation is used to run a piece of code after all tests in the test class have been run?


@AfterEach  

@AfterAll  

@AfterTest  

@After

Answer:  


@AfterAll



Question 9

In TestNG, which annotation is equivalent to JUnit's @BeforeEach?


@BeforeTest  

@BeforeMethod  

@BeforeClass  

@BeforeSuite

Answer:  


@BeforeMethod



Question 10

Which Mockito method is used to verify that a method was called with specific arguments?


verify()  

check()  

assert()  

confirm()

Answer:  


verify()



Question 11

In JUnit 5, which annotation is used to disable a test method?


@Ignore  

@Disabled  

@Skip  

@Deactivate

Answer:  


@Disabled



Question 12

Which of the following is not a lifecycle method in JUnit 5?


@BeforeEach  

@AfterEach  

@BeforeClass  

@BeforeAll

Answer:  


@BeforeClass



Question 13

Which of the following assertions is used to check if a condition is false in JUnit?


assertTrue()  

assertFalse()  

assertNull()  

assertNotNull()

Answer:  


assertFalse()



Question 14

What is the primary purpose of unit testing?


To test the entire application as a whole  

To test individual units or components in isolation  

To test the user interface  

To test the performance of the application

Answer:  


To test individual units or components in isolation



Question 15

In Mockito, which method is used to return a specific value when a method is called?


when().thenReturn()  

doReturn().when()  

mock().thenReturn()  

verify().thenReturn()

Answer:  


when().thenReturn()



Question 16

Which JUnit annotation is used to provide a timeout for a test method?


@Timeout  

@Test(timeout = 1000)  

@TimeLimit  

@Test(timeout = 1)

Answer:  


@Timeout



Question 17

Which of the following is not a valid JUnit assertion?


assertEquals()  

assertNotNull()  

assertThrows()  

assertEmpty()

Answer:  


assertEmpty()



Question 18

Which JUnit 5 annotation is used to run a test multiple times?


@Repeat  

@RepeatedTest  

@LoopTest  

@TestRepeat

Answer:  


@RepeatedTest



Question 19

In TestNG, which annotation is used to indicate that a method should be executed before any test methods in the current class?


@BeforeTest  

@BeforeClass  

@BeforeMethod  

@BeforeSuite

Answer:  


@BeforeClass



Question 20

In Mockito, how can you mock a method to throw an exception?


when(methodCall).thenThrow(new Exception())  

doThrow(new Exception()).when(methodCall)  

throwException(new Exception()).when(methodCall)  

when(methodCall).throw(new Exception())

Answer:  


when(methodCall).thenThrow(new Exception())

Friday, July 12, 2024

Create a function that checks the connection status and reconnects if necessary

 const redis = require('redis');

const { promisify } = require('util'); // Create a Redis client with a connection timeout (in milliseconds) const client = redis.createClient({ host: '127.0.0.1', // Replace with your Redis server host port: 6379, // Replace with your Redis server port if different from default connect_timeout: 10000 // 10 seconds timeout }); // Promisify the `ping` method to check connection const pingAsync = promisify(client.ping).bind(client); // Function to check if connection is available and reconnect if not async function ensureConnection() { try { const pong = await pingAsync(); if (pong === 'PONG') { console.log('Redis connection is healthy'); } else { console.log('Unexpected response from Redis:', pong); await reconnect(); } } catch (err) { console.error('Redis connection error:', err); await reconnect(); } } // Function to reconnect to Redis async function reconnect() { return new Promise((resolve, reject) => { client.quit(); client.connect((err) => { if (err) { console.error('Failed to reconnect to Redis:', err); reject(err); } else { console.log('Reconnected to Redis'); resolve(); } }); }); } // Example usage: Check connection and reconnect if necessary ensureConnection() .then(() => { console.log('Connection check complete'); }) .catch(err => { console.error('Error during connection check:', err); }); // Close the connection gracefully on process exit process.on('exit', () => { client.quit(); }); client.on('error', (err) => { console.error('Redis error:', err); });


  1. Use the following code to check the connection and reconnect if necessary:

const redis = require('redis'); const { promisify } = require('util'); // Create a Redis client with a connection timeout (in milliseconds) const client = redis.createClient({ host: '127.0.0.1', // Replace with your Redis server host port: 6379, // Replace with your Redis server port if different from default connect_timeout: 10000 // 10 seconds timeout }); // Promisify the `ping` method to check connection const pingAsync = promisify(client.ping).bind(client); // Function to check if connection is available and reconnect if not async function ensureConnection() { try { const pong = await pingAsync(); if (pong === 'PONG') { console.log('Redis connection is healthy'); } else { console.log('Unexpected response from Redis:', pong); await reconnect(); } } catch (err) { console.error('Redis connection error:', err); await reconnect(); } } // Function to reconnect to Redis async function reconnect() { return new Promise((resolve, reject) => { // Quit the current client client.quit(() => { // Create a new client instance const newClient = redis.createClient({ host: '127.0.0.1', // Replace with your Redis server host port: 6379, // Replace with your Redis server port if different from default connect_timeout: 10000 // 10 seconds timeout }); // Handle connection events for the new client newClient.on('connect', () => { console.log('Reconnected to Redis'); resolve(newClient); }); newClient.on('error', (err) => { console.error('Failed to reconnect to Redis:', err); reject(err); }); // Replace the old client with the new client client = newClient; }); }); } // Example usage: Check connection and reconnect if necessary ensureConnection() .then(() => { console.log('Connection check complete'); }) .catch(err => { console.error('Error during connection check:', err); }); // Close the connection gracefully on process exit process.on('exit', () => { client.quit(); }); client.on('error', (err) => { console.error('Redis error:', err); });




++++++++++++++++++++++++++++++++++++++++++++++++++++ 3. With timeout
const redis = require('redis'); const { promisify } = require('util'); // Create a Redis client with a connection timeout (in milliseconds) let client = redis.createClient({ host: '127.0.0.1', // Replace with your Redis server host port: 6379, // Replace with your Redis server port if different from default connect_timeout: 10000 // 10 seconds timeout }); // Promisify the `ping` method to check connection const pingAsync = promisify(client.ping).bind(client); // Function to check if connection is available and reconnect if not async function ensureConnection() { return new Promise((resolve, reject) => { const timeout = setTimeout(() => { reject(new Error('Connection check timed out')); }, 5000); // 5 seconds timeout for the connection check pingAsync().then(pong => { clearTimeout(timeout); if (pong === 'PONG') { console.log('Redis connection is healthy'); resolve(); } else { console.log('Unexpected response from Redis:', pong); reconnect().then(resolve).catch(reject); } }).catch(err => { clearTimeout(timeout); console.error('Redis connection error:', err); reconnect().then(resolve).catch(reject); }); }); } // Function to reconnect to Redis async function reconnect() { return new Promise((resolve, reject) => { const timeout = setTimeout(() => { reject(new Error('Reconnection timed out')); }, 10000); // 10 seconds timeout for reconnection // Quit the current client client.quit(() => { // Create a new client instance client = redis.createClient({ host: '127.0.0.1', // Replace with your Redis server host port: 6379, // Replace with your Redis server port if different from default connect_timeout: 10000 // 10 seconds timeout }); // Handle connection events for the new client client.on('connect', () => { clearTimeout(timeout); console.log('Reconnected to Redis'); resolve(); }); client.on('error', (err) => { clearTimeout(timeout); console.error('Failed to reconnect to Redis:', err); reject(err); }); }); }); } // Example usage: Check connection and reconnect if necessary ensureConnection() .then(() => { console.log('Connection check complete'); }) .catch(err => { console.error('Error during connection check:', err); }); // Close the connection gracefully on process exit process.on('exit', () => { client.quit(); }); client.on('error', (err) => { console.error('Redis error:', err); });

FlushDB in Redis in node js

 const express = require('express');

const redis = require('redis'); const { promisify } = require('util'); const app = express(); const PORT = 3000; // Replace with your desired port // Create a Redis client with a connection timeout (in milliseconds) const client = redis.createClient({ host: '127.0.0.1', // Replace with your Redis server host port: 6379, // Replace with your Redis server port if different from default connect_timeout: 10000 // 10 seconds timeout }); // Promisify the `flushdb` method const flushdbAsync = promisify(client.flushdb).bind(client); // Function to flush the Redis database async function flushRedisDatabase() { try { const result = await flushdbAsync(); return { message: 'Database flushed successfully', result }; } catch (err) { console.error('Error flushing database:', err); throw err; } } // REST endpoint to flush the Redis database app.post('/flushdb', async (req, res) => { try { const response = await flushRedisDatabase(); res.status(200).json(response); } catch (err) { res.status(500).json({ error: 'Error flushing database', details: err.message }); } }); // Start the Express server app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); }); // Additional Redis client event handlers for better debugging client.on('connect', () => { console.log('Connected to Redis'); }); client.on('error', (err) => { console.error('Redis error:', err); }); client.on('ready', () => { console.log('Redis client ready'); }); client.on('reconnecting', () => { console.log('Reconnecting to Redis...'); }); client.on('end', () => { console.log('Redis connection closed'); });


Wednesday, July 10, 2024

Redis connection in node js

 import redis from 'redis';

// Create a Redis client with retry strategy const client = redis.createClient({ host: 'localhost', // Replace with your Redis server host port: 6379, // Replace with your Redis server port retry_strategy: function (options) { // options.error contains the error object returned by the last attempt to connect if (options.error && options.error.code === 'ECONNREFUSED') { // If the connection was refused by the server, log the error and stop retrying console.error('The server refused the connection'); return new Error('The server refused the connection'); } // options.total_retry_time is the total time (in milliseconds) that the client has been trying to reconnect if (options.total_retry_time > 1000 * 60 * 60) { // If the total retry time exceeds 1 hour, log the error and stop retrying console.error('Retry time exhausted'); return new Error('Retry time exhausted'); } // options.attempt is the number of retry attempts so far if (options.attempt > 10) { // If the number of retry attempts exceeds 10, log the error and stop retrying console.error('Too many retry attempts'); return undefined; } // Reconnect after a specific time, which increases with each attempt // options.attempt * 100 gives a delay that increases by 100ms with each attempt // Math.min ensures the delay does not exceed 3000ms (3 seconds) return Math.min(options.attempt * 100, 3000); } }); // Event listener for successful connection client.on('connect', function() { console.log('Redis client connected'); }); // Event listener for errors client.on('error', function (err) { console.error('Something went wrong ' + err); }); export default client;

Redis connection in node js

 import redis from 'redis';

// Create a Redis client with retry strategy const client = redis.createClient({ host: 'localhost', // Replace with your Redis server host port: 6379, // Replace with your Redis server port retry_strategy: function (options) { if (options.error && options.error.code === 'ECONNREFUSED') { // End reconnecting on a specific error and flush all commands with a individual error console.error('The server refused the connection'); return new Error('The server refused the connection'); } if (options.total_retry_time > 1000 * 60 * 60) { // End reconnecting after a specific timeout and flush all commands with a individual error console.error('Retry time exhausted'); return new Error('Retry time exhausted'); } if (options.attempt > 10) { // End reconnecting with built in error console.error('Too many retry attempts'); return undefined; } // Reconnect after a specific time return Math.min(options.attempt * 100, 3000); } }); client.on('connect', function() { console.log('Redis client connected'); }); client.on('error', function (err) { console.error('Something went wrong ' + err); }); export default client;

Thursday, June 13, 2024

Clear cache || FlushDB || Clear Redis Cache ||Node js ||aws

Clear cache || FlushDB || Clear Redis Cache ||Node js ||aws 



const express = require('express');

const redis = require('redis'); const app = express(); const port = 3000; // Replace with your actual hostname and port const client = redis.createClient({ host: 'your-elasticache-hostname', port: your-elasticache-port }); client.on('error', (err) => { console.log("Error " + err); }); app.get('/flushall', (req, res) => { client.flushdb((err, succeeded) => { if (err) { res.status(500).send({ error: 'Failed to flush Redis cache' }); } else { res.send({ message: 'Redis cache successfully flushed' }); } }); }); app.listen(port, () => { console.log(`App running on port ${port}`); });

===============================
Method 2: with lamda 

const Redis = require('ioredis'); exports.handler = async (event, context) => { const redis = new Redis({ host: 'YOUR_REDIS_HOST', // replace with your host port: YOUR_REDIS_PORT, // replace with your port password: 'YOUR_REDIS_PASSWORD', // replace with your password (if any) db: 0, }); try { // Ping Redis to check connection const ping = await redis.ping(); console.log('Ping:', ping); // Clear all keys await redis.flushdb(); console.log('Cache cleared'); return { statusCode: 200, body: 'Cache cleared' }; } catch (error) { console.log('Error:', error); return { statusCode: 500, body: 'Error clearing cache' }; } finally { // Disconnect from Redis await redis.quit(); } };

=============================================
Methos 3: with redis dependency: const redis = require('redis'); exports.handler = async (event, context) => { return new Promise((resolve, reject) => { const client = redis.createClient({ host: 'YOUR_REDIS_HOST', // replace with your host port: YOUR_REDIS_PORT, // replace with your port password: 'YOUR_REDIS_PASSWORD', // replace with your password (if any) db: 0, }); client.on('connect', function() { console.log('Connected to Redis'); client.flushdb(function (err, succeeded) { if (err) { console.error('Error:', err); reject({ statusCode: 500, body: 'Error clearing cache' }); } else { console.log('Cache cleared'); resolve({ statusCode: 200, body: 'Cache cleared' }); } // Disconnect from Redis client.quit(); }); }); client.on('error', function (err) { console.error('Error:', err); reject({ statusCode: 500, body: 'Error clearing cache' }); }); }); };

Sunday, May 19, 2024

Calculate your Age

Calculate Age Age Calculator

Age Calculator

Friday, February 16, 2024

what is meant by --max-request-journal-entries and --no-request-journal in wiremock configuration

max-request-journal-entries and no-request-journal in wiremock configuration


In WireMock, the request journal is a built-in feature that keeps a record of incoming requests and their corresponding responses. It can be helpful for debugging and analysis purposes.


--max-request-journal-entries is an option that allows you to set a limit on the number of requests that the request journal stores. When this limit is reached, older requests will be removed from the journal to make room for new ones. By setting this option, you can control the memory usage of the request journal.


For example, using --max-request-journal-entries=10000 will limit the request journal to store a maximum of 10,000 requests.


--no-request-journal is an option that disables the request journal entirely. When this option is used, WireMock will not store any requests or responses in the request journal. Disabling the request journal can help reduce memory consumption and improve performance, especially during load testing or in production environments where request logging is not necessary.


In summary:


--max-request-journal-entries: Sets a limit on the number of requests stored in the request journal.

--no-request-journal: Disables the request journal completely.

Thursday, January 18, 2024

Sort an array of 0s, 1s and 2s | Dutch National Flag problem

Sort an array of 0s, 1s and 2s |

Dutch National Flag problem


👀👀👀👀👀


/*

* This program defines a sortArray() method that sorts

* an array of 0s, 1s, and 2s using

* the Dutch National Flag algorithm.

*/


public class Sort012 {


public static void swap(int[] arr,int i,int j) {

int temp;

temp=arr[i];

arr[i]=arr[j];

arr[j]=temp;

}

public static void sortArray(int[] arr) {

int low =0;

int mid =0;

int high =arr.length-1;

while(mid<=high) {

switch (arr[mid]) {

case 0:

swap(arr,low,mid);

low++;

mid++;

break;

case 1:

mid++;

break;

case 2:

swap(arr,mid,high);

high--;

break;

default:

break;

}

}

}


public static void main(String... aa) {

int arr[]= {2,0,1,0,2,1,2,0,1,0,2,1};

sortArray(arr);

for(int i:arr) {

System.out.print(i+" ");

}

}

}


Output:

0 0 0 0 1 1 1 1 2 2 2 2



Wednesday, January 17, 2024

Merge two sorted linked lists


Merge two sorted linked lists


public class MergeLinkedLists {

static class ListNode {

int val;

ListNode next;

public ListNode() {}


public ListNode(int val) {

this.val = val;

}


public ListNode(int val, ListNode next) {

this.val = val;

this.next = next;

}

}

public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {

ListNode mergedList = new ListNode();

ListNode current = mergedList;


while (list1 != null && list2 != null) {

if (list1.val <= list2.val) {

current.next = list1;

list1 = list1.next;

} else {

current.next = list2;

list2 = list2.next;

}

current = current.next;

}


if (list1 != null) {

current.next = list1;

} else {

current.next = list2;

}


return mergedList.next;

}


public static void main(String[] args) {

// Example usage:

ListNode list1 = new ListNode(1, new ListNode(2, new ListNode(4)));

ListNode list2 = new ListNode(1, new ListNode(3, new ListNode(4)));


ListNode mergedList = mergeTwoLists(list1, list2);

while (mergedList != null) {

System.out.print(mergedList.val + " ");

mergedList = mergedList.next;

}

}

}


Time Complexity: O(M + N), Where M and N are the size of the list1 and list2 respectively.
Auxiliary Space: O(M+N), Function call stack space


Output:


1 1 2 3 4 4


Geeks link:

    Merge To Linked List


Monday, January 15, 2024

Python script to automate login and extract cookie

 pip install requests

*****************create file*****************

import requests

url_login = "https://example.com/login" # Replace with the actual login URL url_after_login = "https://example.com/next" # Replace with the actual URL after login # Replace with your actual username and password payload = { "username": "your_username", "password": "your_password" } # Create a session to persist cookies session = requests.Session() # Perform the login response_login = session.post(url_login, data=payload) # Check if login was successful (replace '200' with the appropriate success status code) if response_login.status_code == 200: print("Login successful") # Perform the action after login (e.g., skip OTP) response_after_login = session.get(url_after_login) # Get the value of the desired cookie (replace 'cookie_name' with the actual cookie name) cookie_value = session.cookies.get("cookie_name") if cookie_value: print(f"The value of the cookie is: {cookie_value}") else: print("The desired cookie was not found.") else: print("Login failed.")

**********************************************

save login_script.py
python login_script.py

Create a Digital Clock using HTML and JavaScript

Create a Digital Clock using HTML and JavaScript  <! DOCTYPE html> < html > < head > <...

Followers

Search This Blog

Popular Posts