/*
 * SonarQube
 * Copyright (C) 2009-2024 SonarSource SA
 * mailto:info AT sonarsource DOT com
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package org.sonar.server.async;

import java.lang.management.ManagementFactory;
import javax.annotation.CheckForNull;
import javax.management.InstanceNotFoundException;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import org.junit.Test;
import org.mockito.Mockito;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

public class AsyncExecutionMBeanImplTest {
  private AsyncExecutionMonitoring asyncExecutionMonitoring = Mockito.mock(AsyncExecutionMonitoring.class);

  private AsyncExecutionMBeanImpl underTest = new AsyncExecutionMBeanImpl(asyncExecutionMonitoring);

  @Test
  public void register_and_unregister() throws Exception {
    assertThat(getMBean()).isNull();

    underTest.start();
    assertThat(getMBean()).isNotNull();

    underTest.stop();
    assertThat(getMBean()).isNull();
  }

  @Test
  public void getQueueSize_delegates_to_AsyncExecutionMonitoring() {
    when(asyncExecutionMonitoring.getQueueSize()).thenReturn(12);

    assertThat(underTest.getQueueSize()).isEqualTo(12);

    verify(asyncExecutionMonitoring).getQueueSize();
  }

  @Test
  public void getWorkerCount_delegates_to_AsyncExecutionMonitoring() {
    when(asyncExecutionMonitoring.getWorkerCount()).thenReturn(12);

    assertThat(underTest.getWorkerCount()).isEqualTo(12);

    verify(asyncExecutionMonitoring).getWorkerCount();
  }

  @Test
  public void getLargestWorkerCount_delegates_to_AsyncExecutionMonitoring() {
    when(asyncExecutionMonitoring.getLargestWorkerCount()).thenReturn(12);

    assertThat(underTest.getLargestWorkerCount()).isEqualTo(12);

    verify(asyncExecutionMonitoring).getLargestWorkerCount();
  }

  @CheckForNull
  private ObjectInstance getMBean() throws Exception {
    try {
      return ManagementFactory.getPlatformMBeanServer().getObjectInstance(new ObjectName(AsyncExecutionMBean.OBJECT_NAME));
    } catch (InstanceNotFoundException e) {
      return null;
    }
  }


}
