More filesys tests.
[pintos-anon] / grading / filesys / random.inc
1 /* -*- c -*- */
2
3 #include <random.h>
4 #include <stdio.h>
5 #include <string.h>
6 #include <syscall.h>
7 #include "fslib.h"
8
9 #if TEST_SIZE % BLOCK_SIZE != 0
10 #error TEST_SIZE must be a multiple of BLOCK_SIZE
11 #endif
12
13 #define BLOCK_CNT (TEST_SIZE / BLOCK_SIZE)
14
15 char buf[TEST_SIZE];
16 int order[BLOCK_CNT];
17
18 void
19 test_main (void) 
20 {
21   int fd;
22   size_t i;
23
24   random_init (57);
25   random_bytes (buf, sizeof buf);
26
27   for (i = 0; i < BLOCK_CNT; i++)
28     order[i] = i;
29
30   check (create ("bazzle", TEST_SIZE), "create \"bazzle\"");
31   check ((fd = open ("bazzle")) > 1, "open \"bazzle\"");
32
33   msg ("write \"bazzle\" in random order");
34   shuffle (order, BLOCK_CNT, sizeof *order);
35   for (i = 0; i < BLOCK_CNT; i++) 
36     {
37       size_t ofs = BLOCK_SIZE * order[i];
38       seek (fd, ofs);
39       if (write (fd, buf + ofs, BLOCK_SIZE) <= 0)
40         fail ("write %d bytes at offset %zu failed", (int) BLOCK_SIZE, ofs);
41     }
42
43   msg ("read \"bazzle\" in random order");
44   shuffle (order, BLOCK_CNT, sizeof *order);
45   for (i = 0; i < BLOCK_CNT; i++) 
46     {
47       char block[BLOCK_SIZE];
48       size_t ofs = BLOCK_SIZE * order[i];
49       seek (fd, ofs);
50       if (read (fd, block, BLOCK_SIZE) <= 0)
51         fail ("read %d bytes at offset %zu failed", (int) BLOCK_SIZE, ofs);
52       if (memcmp (block, buf + ofs, BLOCK_SIZE)) 
53         {
54           printf ("Expected data:\n");
55           hex_dump (ofs, buf + ofs, BLOCK_SIZE, false);
56           printf ("Actually read data:\n");
57           hex_dump (ofs, block, BLOCK_SIZE, false);
58           fail ("%d bytes at offset %zu differed from expected",
59                 (int) BLOCK_SIZE, ofs);
60         }
61     }
62
63   fail ("close \"bazzle\"");
64   close (fd);
65 }