Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions src/__tests__/RiskInsert.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
const { ObjectId } = require('mongodb');
const { createRiskGame } = require('../database-scripts/Risk/RiskInsert');
const { connectToDatabase } = require('../mongoConnection');

// Mock MongoDB client and collection
jest.mock('../mongoConnection', () => ({
connectToDatabase: jest.fn(),
client: {
db: jest.fn(() => ({
collection: jest.fn(() => ({
findOne: jest.fn(),
deleteOne: jest.fn(),
insertOne: jest.fn(() => ({
insertedId: 'some-id' // Replace 'some-id' with an ObjectId string
})),
updateOne: jest.fn() // Mock the updateOne method
})),
})),
close: jest.fn(),
},
}));

describe('createRiskGame', () => {
let userData, gameInfo;

beforeEach(() => {
let mockUserId = '507f191e810c19729de860ea'; // A valid ObjectId string
userData = {
_id: mockUserId,
games_played: 0,
balance: 100,
};
gameInfo = {
gameMode: 'Local',
playerNames: ['Player 1', 'Player 2'],
players: [
{ name: 'Player 1', armies: 10 },
{ name: 'Player 2', armies: 10 },
],
};
});

afterEach(() => {
jest.clearAllMocks();
});

it('should create a new Risk game', async () => {
await createRiskGame(userData, gameInfo);
expect(connectToDatabase).toHaveBeenCalledTimes(2);
expect(connectToDatabase).toHaveBeenCalledWith();
// Add more expectations as needed
});

// Add more test cases as needed
});
64 changes: 64 additions & 0 deletions src/__tests__/RiskUpdate.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
const { updateRiskGame } = require('../database-scripts/Risk/RiskUpdate');
const { connectToDatabase } = require('../mongoConnection');

jest.mock('../mongoConnection', () => ({
connectToDatabase: jest.fn(),
client: {
db: jest.fn(() => ({
collection: jest.fn(() => ({
updateOne: jest.fn()
}))
})),
close: jest.fn()
}
}));

describe('updateRiskGame', () => {
afterEach(() => {
jest.clearAllMocks();
});

it('should update local risk game information', async () => {
// Mock data
const gameData = {
_id: '507f191e810c19729de860ea', // Replace with a valid ObjectId string
game_mode: 'Local',
playerNames: ['Player 1', 'Player 2'],
players: [
{ name: 'Player 1', armies: 10 },
{ name: 'Player 2', armies: 10 },
],
territories: [
{ name: 'Alaska', owner: null, armies: 3 },
// Add other territories as needed
],
player_turn: 'Player 1', // Assuming Player 1 is the first player
winner: null,
game_phase: 'reinforcement',
control: [
{
region: 'North America',
connections: [
// Add connections as needed
],
owner: null
},
// Add other continents as needed
],
Cards: [], // Assuming an empty array for cards
created_at: new Date(),
updated_at: new Date()
};

// Call the function
await updateRiskGame(gameData);

// Assertions
expect(connectToDatabase).toHaveBeenCalledTimes(1);
expect(connectToDatabase).toHaveBeenCalledWith();

// Add more expectations as needed
});

// Add more test cases as needed
});
39 changes: 39 additions & 0 deletions src/__tests__/UserInsert.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
const { createUser } = require('../database-scripts/User/UserInsert');
const { connectToDatabase } = require('../mongoConnection');

jest.mock('../mongoConnection', () => ({
connectToDatabase: jest.fn(),
client: {
db: jest.fn(() => ({
collection: jest.fn(() => ({
insertOne: jest.fn()
}))
})),
close: jest.fn()
}
}));

describe('createUser', () => {
afterEach(() => {
jest.clearAllMocks();
});

it('should create a new user', async () => {
// Mock data
const userName = 'testUser';
const password = 'testPassword';
const email = 'test@example.com';
const avatar = 'avatar.jpg';

// Call the function
await createUser(userName, password, email, avatar);

// Assertions
expect(connectToDatabase).toHaveBeenCalledTimes(1);
expect(connectToDatabase).toHaveBeenCalledWith();

// Add more expectations as needed
});

// Add more test cases as needed
});
70 changes: 70 additions & 0 deletions src/__tests__/rules_test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
// tests/unit/test_functions.js

// Import the functions to test
const { getPlayerIndexByName, getCardIndexByName } = require('C:/Users/nesze/CS320/cs320-project/src/html/scripts/gamez/Risk/Risk_rules.js').getPlayerIndexByName;

// Mock gameData for testing
const gameData = {
players: [
{ name: "Alice" },
{ name: "Bob" },
{ name: "Charlie" }
],
Cards: [
{ territory: { name: "Card1" } },
{ territory: { name: "Card2" } },
{ territory: { name: "Card3" } }
]
};


// Define a simple assert function to check conditions
function assert(condition, message) {
if (!condition) {
throw new Error(message);
}
}

// Test cases for getPlayerIndexByName
function testGetPlayerIndexByName() {
// Test case 1: Finds the index of an existing player by name
assert(getPlayerIndexByName("Bob", gameData) === 1, "Test case 1 failed");

// Test case 2: Returns -1 when player with given name is not found
assert(getPlayerIndexByName("David", gameData) === -1, "Test case 2 failed");

// Test case 3: Returns -1 when gameData.players is empty
const emptyGameData = { players: [] };
assert(getPlayerIndexByName("Alice", emptyGameData) === -1, "Test case 3 failed");

// Test case 4: Returns -1 when playerName is not a string
assert(getPlayerIndexByName(123, gameData) === -1, "Test case 4 failed");

// Add more test cases for getPlayerIndexByName as needed
}

function testGetCardIndexByName() {
// Test case 1: Finds the index of an existing card by name
assert(getCardIndexByName("Card2", gameData) === 1, "Test case 1 failed");

// Test case 2: Returns -1 when card with given name is not found
assert(getCardIndexByName("Card4", gameData) === -1, "Test case 2 failed");

// Test case 3: Returns -1 when gameData.Cards is empty
const emptyGameData = { Cards: [] };
assert(getCardIndexByName("Card1", emptyGameData) === -1, "Test case 3 failed");

// Test case 4: Returns -1 when gainedCard is not a string
assert(getCardIndexByName(123, gameData) === -1, "Test case 4 failed");

// Add more test cases as needed
}

// Run all tests
function runAllTests() {
testGetPlayerIndexByName();
testGetCardIndexByName();
}

// Run all tests
runAllTests();
35 changes: 35 additions & 0 deletions src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,41 @@ const server = http.createServer((req, res) => {
filePath = path.join(__dirname, 'index.html');
}

if(req.method == 'POST' && req.url === '/submit'){
console.log('Handling POST request for /bugz.html');
let data = '';

// Collect data from the request
req.on('data', (chunk) => {
console.log('Data chunk received:', chunk);
data += chunk;
});

// Process the collected data when the request ends
req.on('end', async () => {
try {
// Parse the form data
console.log('Received form data:', data);
const formData = querystring.parse(data);
console.log('Parsed form data:', formData);

// Now 'formData' will contain the user input
const Bug = formData.bugTitle;
const detail = formData.bugDescription;

// Move MongoDB operations here
await createUser(Bug, detail); // make handle for bugpg

// Respond to the client
res.end('Bug submitted successfully!');
} catch (error) {
console.error('Error processing form data:', error);
res.end('Internal Server Error');
}
});
return;
}

// Check if the requested file is within the html directory
if (filePath.indexOf(__dirname) !== 0) {
res.writeHead(403);
Expand Down
Loading