@Test
  public void testRetainAssignmentOnClusterRestart() throws Exception {
    setupCluster();
    HMaster master = UTIL.getMiniHBaseCluster().getMaster();
    SingleProcessHBaseCluster cluster = UTIL.getHBaseCluster();
    List<JVMClusterUtil.RegionServerThread> threads = cluster.getLiveRegionServerThreads();
    assertEquals(NUM_OF_RS, threads.size());
    int[] rsPorts = new int[NUM_OF_RS];
    for (int i = 0; i < NUM_OF_RS; i++) {
      rsPorts[i] = threads.get(i).getRegionServer().getServerName().getPort();
    }

    // We don't have to use SnapshotOfRegionAssignmentFromMeta. We use it here because AM used to
    // use it to load all user region placements
    SnapshotOfRegionAssignmentFromMeta snapshot =
      new SnapshotOfRegionAssignmentFromMeta(master.getConnection());
    snapshot.initialize();
    Map<RegionInfo, ServerName> regionToRegionServerMap = snapshot.getRegionToRegionServerMap();
    for (ServerName serverName : regionToRegionServerMap.values()) {
      boolean found = false; // Test only, no need to optimize
      for (int k = 0; k < NUM_OF_RS && !found; k++) {
        found = serverName.getPort() == rsPorts[k];
      }
      assertTrue(found);
    }

    LOG.info("\n\nShutting down HBase cluster");
    cluster.stopMaster(0);
    cluster.shutdown();
    cluster.waitUntilShutDown();

    LOG.info("\n\nSleeping a bit");
    Thread.sleep(2000);

    LOG.info("\n\nStarting cluster the second time with the same ports");
    cluster.getConf().setInt(ServerManager.WAIT_ON_REGIONSERVERS_MINTOSTART, 3);
    master = cluster.startMaster().getMaster();
    for (int i = 0; i < NUM_OF_RS; i++) {
      cluster.getConf().setInt(HConstants.REGIONSERVER_PORT, rsPorts[i]);
      cluster.startRegionServer();
    }

    ensureServersWithSamePort(master, rsPorts);

    // Wait till master is initialized and all regions are assigned
    for (TableName TABLE : TABLES) {
      UTIL.waitTableAvailable(TABLE);
    }
    UTIL.waitUntilNoRegionsInTransition(60000);

    snapshot = new SnapshotOfRegionAssignmentFromMeta(master.getConnection());
    snapshot.initialize();
    Map<RegionInfo, ServerName> newRegionToRegionServerMap = snapshot.getRegionToRegionServerMap();
    assertEquals(regionToRegionServerMap.size(), newRegionToRegionServerMap.size());
    for (Map.Entry<RegionInfo, ServerName> entry : newRegionToRegionServerMap.entrySet()) {
      ServerName oldServer = regionToRegionServerMap.get(entry.getKey());
      ServerName currentServer = entry.getValue();
      LOG.info(
        "Key=" + entry.getKey() + " oldServer=" + oldServer + ", currentServer=" + currentServer);
      assertEquals(entry.getKey().toString(), oldServer.getAddress(), currentServer.getAddress());
      assertNotEquals(oldServer.getStartcode(), currentServer.getStartcode());
    }
  }
This tests retaining assignments on a cluster restart
hbase-server/src/test/java/org/apache/hadoop/hbase/master/TestRetainAssignmentOnRestart.java